Component和Configuration注解区别实例详解
作者:AlvinYueChao 发布时间:2022-04-17 01:12:24
引言
第一眼看到这个题目,我相信大家都会脑子里面弹出来一个想法:这不都是 Spring 的注解么,加了这两个注解的类都会被最终封装成 BeanDefinition 交给 Spring 管理,能有什么区别?
首先先给大家看一段示例代码:
AnnotationBean.java
import lombok.Data;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
//@Configuration
public class AnnotationBean {
@Qualifier("innerBean1")
@Bean()
public InnerBean innerBean1() {
return new InnerBean();
}
@Bean
public InnerBeanFactory innerBeanFactory() {
InnerBeanFactory factory = new InnerBeanFactory();
factory.setInnerBean(innerBean1());
return factory;
}
public static class InnerBean {
}
@Data
public static class InnerBeanFactory {
private InnerBean innerBean;
}
}
AnnotationTest.java
@Test
void test7() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BASE_PACKAGE);
Object bean1 = applicationContext.getBean("innerBean1");
Object factoryBean = applicationContext.getBean("innerBeanFactory");
int hashCode1 = bean1.hashCode();
InnerBean innerBeanViaFactory = ((InnerBeanFactory) factoryBean).getInnerBean();
int hashCode2 = innerBeanViaFactory.hashCode();
Assertions.assertEquals(hashCode1, hashCode2);
}
大家可以先猜猜看,这个test7()的执行结果究竟是成功呢还是失败呢?
答案是失败的。如果将AnnotationBean的注解从 @Component 换成 @Configuration,那test7()就会执行成功。
究竟是为什么呢?通常 Spring 管理的 bean 不都是单例的么?
别急,让笔者慢慢道来 ~~~
Spring-source-5.2.8 两个注解声明
以下是摘自 Spring-source-5.2.8 的两个注解的声明
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
String value() default "";
}
---------------------------------- 这是分割线 -----------------------------------
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
/**
* Explicitly specify the name of the Spring bean definition associated with the
* {@code @Configuration} class. If left unspecified (the common case), a bean
* name will be automatically generated.
* <p>The custom name applies only if the {@code @Configuration} class is picked
* up via component scanning or supplied directly to an
* {@link AnnotationConfigApplicationContext}. If the {@code @Configuration} class
* is registered as a traditional XML bean definition, the name/id of the bean
* element will take precedence.
* @return the explicit component name, if any (or empty String otherwise)
* @see AnnotationBeanNameGenerator
*/
@AliasFor(annotation = Component.class)
String value() default "";
/**
* Specify whether {@code @Bean} methods should get proxied in order to enforce
* bean lifecycle behavior, e.g. to return shared singleton bean instances even
* in case of direct {@code @Bean} method calls in user code. This feature
* requires method interception, implemented through a runtime-generated CGLIB
* subclass which comes with limitations such as the configuration class and
* its methods not being allowed to declare {@code final}.
* <p>The default is {@code true}, allowing for 'inter-bean references' via direct
* method calls within the configuration class as well as for external calls to
* this configuration's {@code @Bean} methods, e.g. from another configuration class.
* If this is not needed since each of this particular configuration's {@code @Bean}
* methods is self-contained and designed as a plain factory method for container use,
* switch this flag to {@code false} in order to avoid CGLIB subclass processing.
* <p>Turning off bean method interception effectively processes {@code @Bean}
* methods individually like when declared on non-{@code @Configuration} classes,
* a.k.a. "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore
* behaviorally equivalent to removing the {@code @Configuration} stereotype.
* @since 5.2
*/
boolean proxyBeanMethods() default true;
}
从这两个注解的定义中,可能大家已经看出了一点端倪:@Configuration 比 @Component 多一个成员变量 boolean proxyBeanMethods()
默认值是 true. 从这个成员变量的注释中,我们可以看到一句话
Specify whether {@code @Bean} methods should get proxied in order to enforce bean lifecycle behavior, e.g. to return shared singleton bean instances even in case of direct {@code @Bean} method calls in user code.
其实从这句话,我们就可以初步得到我们想要的答案了:在带有 @Configuration 注解的类中,一个带有 @Bean 注解的方法显式调用另一个带有 @Bean 注解的方法,返回的是共享的单例对象. 下面我们从 Spring 源码实现角度来看看这中间的原理.
从 Spring 源码实现中可以得出一个规律,Spring 作者在实现注解时,通常是先收集解析,再调用。@Configuration是 基于 @Component 实现的,在 @Component 的解析过程中,我们可以看到下面一段逻辑:
org.springframework.context.annotation.ConfigurationClassUtils#checkConfigurationClassCandidate
Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
else if (config != null || isConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
默认情况下,Spring 在将带有 @Configuration 注解的类封装成 BeanDefinition 的时候,会设置一个属性 CONFIGURATION_CLASS_ATTRIBUTE
,属性值为 CONFIGURATION_CLASS_FULL
, 反之,如果只有 @Component 注解,那该属性值就会是 CONFIGURATION_CLASS_LITE
(这个属性值很重要). 在 @Component 注解的调用过程当中,有下面一段逻辑:
org.springframework.context.annotation.ConfigurationClassPostProcessor#enhanceConfigurationClasses
for (String beanName : beanFactory.getBeanDefinitionNames()) {
......
if ((configClassAttr != null || methodMetadata != null) && beanDef instanceof AbstractBeanDefinition) {
......
if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
if (!(beanDef instanceof AbstractBeanDefinition)) {
throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
}
else if (logger.isInfoEnabled() && beanFactory.containsSingleton(beanName)) {
logger.info("Cannot enhance @Configuration bean definition '" + beanName +
"' since its singleton instance has been created too early. The typical cause " +
"is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
"return type: Consider declaring such methods as 'static'.");
}
configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
}
}
}
if (configBeanDefs.isEmpty()) {
// nothing to enhance -> return immediately
return;
}
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
......
如果 BeanDefinition 的 ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE
属性值为 ConfigurationClassUtils.CONFIGURATION_CLASS_FULL
, 则该 BeanDefinition 对象会被加入到 Map<String, AbstractBeanDefinition> configBeanDefs
容器中。
如果 Spring 发现该 Map 是空的,则认为不需要进行代理增强,立即返回;反之,则为该类 (本文中,被代理类即为 AnnotationBean, 以下简称该类) 创建代理。
所以如果该类的注解是 @Component,调用带有 @Bean 注解的 innerBean1() 方法时,this 对象为 Spring 容器中的真实单例对象,例如 AnnotationBean@4149
.
@Bean
public InnerBeanFactory innerBeanFactory() {
InnerBeanFactory factory = new InnerBeanFactory();
factory.setInnerBean(innerBean1());
return factory;
}
那在上述方法中每调用一次 innerBean1() 方法时,势必会返回一个新创建的 InnerBean 对象。如果该类的注解为 @Configuration 时,this 对象为 Spring 生成的 AnnotationBean 的代理对象,例如 AnnotationBean$$EnhancerBySpringCGLIB$$90f8540c@4296
,
增强逻辑
// The callbacks to use. Note that these callbacks must be stateless.
private static final Callback[] CALLBACKS = new Callback[] {
new BeanMethodInterceptor(),
new BeanFactoryAwareMethodInterceptor(),
NoOp.INSTANCE
};
----------------------------------- 这是分割线 -------------------------------
/**
* Creates a new CGLIB {@link Enhancer} instance.
*/
private Enhancer newEnhancer(Class<?> configSuperClass, @Nullable ClassLoader classLoader) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(configSuperClass);
enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
enhancer.setUseFactory(false);
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
enhancer.setCallbackFilter(CALLBACK_FILTER);
enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
return enhancer;
}
当在上述方法中调用 innerBean1() 时,ConfigurationClassEnhancer 遍历 3 种回调方法判断当前调用应该使用哪个回调方法时,第一个回调类型匹配成功org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#isMatch
匹配过程如下所示:
@Override
public boolean isMatch(Method candidateMethod) {
return (candidateMethod.getDeclaringClass() != Object.class && !BeanFactoryAwareMethodInterceptor.isSetBeanFactory(candidateMethod) && BeanAnnotationHelper.isBeanAnnotated(candidateMethod));
}
匹配成功之后,使用 org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#intercept
对 innerBean1() 方法调用进行拦截. 在本例中,innerBean1() 被增强器调用了两次,第一次调用是 Spring 解析带有 @Bean 注解的 innerBean1() 方法,将构造的 InnerBean 对象加入 Spring 单例池中. 第二次调用是 Spring 解析带有 @Bean 注解的 innerBeanFactory() 方法,在该方法中显式调用 innerBean1(). 在第二次调用时,增强过程如下所示:org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#resolveBeanReference
Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) : beanFactory.getBean(beanName));
看到这里,相信大家和笔者一样,对 @Component 和 @Configuration 注解的区别豁然开朗:
默认情况下,带有 @Configuration 的类在被 Spring 解析时,会使用切面进行字节码增强,在解析带有 @Bean的方法 innerBeanFactory() 时,该方法内部显式调用了另一个带有 @Bean 注解的方法 innerBean1(), 那么返回的对象和 Spring 第一次解析带有 @Bean 注解的方法 innerBean1() 生成的单例对象是同一个.
来源:https://segmentfault.com/a/1190000040726724
猜你喜欢
- 文件作为存储数据的单元,会根据数据类型产生很多分类,也就是所谓的文件类型。在对数据文件进行操作时,常常需要根据不同的文件类型来作不同的处理。
- springboot结合maven配置不同环境的profile1、在spring-boot中新建配置文件spring-boot不同环境配置文
- 很多公司由于历史原因,都会有自研的RPC框架。尤其是在2015-2017期间,Spring Cloud刚刚面世,Dubbo停止维护多年,很多
- C#小程序飞行棋,程序效果图1、设计分析这个程序界面大致分为四部分:① 最上面游戏名字界面②信息提示区③游戏界面区④游戏操作提示区2、分区设
- 一、创建资源文件可以将字符串、图像或对象数据等资源包含在资源文件中,方便应用程序使用。创建资源文件的方法:1、手动或使用IDE工具自动生成X
- 在学习操作系统这本书的时候,我们使用的是汤小丹老师的《计算机操作系统》接下来我将会使用java语言去实现内部代码。Swap指令最佳置换算法是
- 简介方案对比本处列举表示类型或状态的常用方法的对比。法1:使用数字表示(不推荐)//1:支付宝支付;2:微信支付;3:银行卡支付privat
- 介绍在 .NET4.0 之前,如果我们需要在多线程环境下使用 Dictionary 类,除了自己实现线程同步来保证线程安全外,我们没有其他选
- 1、事务介绍事务(Transaction),一般是指要做的或所做的事情。在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元
- 一. 泛型概念的提出(为什么需要泛型)?首先,我们看下下面这段简短的代码:public class GenericTest {public
- 在 String 中提供了两个截取字符串的方法,一个是从指定位置截取到字符串结尾,另一个是截取指定范围的内容。下面对这两种方法分别进行介绍。
- 前言将采用slf+log4j2方式进行打印日志,以下用两种方式,一种基于maven的springboot2,一种jdk6,普通jar包的sp
- 创建一个maven项目导入springboot依赖,注意底 * 释部分<?xml version="1.0&quo
- 命令模式定义:将请求封装成对象,这可以让你使用不同的请求、队列、或者日志来参数化其他对象。何时使用命令模式?当需要将发出请求的对象和执行请求
- spring与IoCIoC:控制反转,将由代码操纵的对象控制权,交给第三方容器,反转给第三方容器。这种对象依赖的关系管理方式,称作IoC。I
- 前言Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案,Nacos 作为其核心组件之一,可以作为注册中心和配置中
- 文件输出为字符串示例代码:/** * 读取文件为字符串 * * @return */pub
- Kotlin基础教程之数据类型一切都是对象.在Kotlin中一切都是对象.Kotlin有一些基本类型Boolean,Byte,Shot,In
- 本篇文章主要介绍泛型的应用。泛型是.NET work 2.0 版类库就已经提供的语法,主要用于提高代码的可重用性、类型安全性和效
- 本篇和大家分享的是通过maven对springboot中打war包和jar包;war通常来说生成后直接放到tomcat的webapps下面就