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


猜你喜欢
- 本文实例讲述了java实现递归文件列表的方法。分享给大家供大家参考。具体如下:FileListing.java如下:import java.
- java8的stream流能完美解对象集合去重问题. List<UserCar> list1 = new ArrayList()
- 对于QQ截图,肯定是早就有认识了,只是一直没有去认真观察这个操作的具体实现步骤。所以这里将自己的记忆中的步骤简单的写一下:习惯性用QQ或者T
- 本文实例为大家分享了Unity3D Ui利用shader添加效果的具体代码,供大家参考,具体内容如下// Upgrade NOTE: rep
- 前言研究表明,Java堆中对象占据最大比重的就是字符串对象,所以弄清楚字符串知识很重要,本文主要重点聊聊字符串常量池。Java中的字符串常量
- 一般来说, 泛型的作用就类似一个占位符, 或者说是一个参数, 可以让我们把类型像参数一样进行传递, 尽可能地复用代码。我有个朋友, 在使用的
- 状态分类在Hibernate框架中,为了管理持久化类,Hibernate将其分为了三个状态:瞬时态(Transient Object)持久态
- 本文实例讲述了Android编程开发ScrollView中ViewPager无法正常滑动问题解决方法。分享给大家供大家参考,具体如下:这里主
- 1 在图片上用鼠标进行操作,opencv主要用到setMouseCallback()函数。winname 窗口名称onMouse 鼠标事件的
- 在最近的项目中有个需求是这样的:入参封装成JSON,EXAMPLE:{ "uuid": "iamauuid&q
- AES简介AES(The Advanced Encryption Standard)是美国国家标准与技术研究所用于加密电子数据的规范。它被预
- 实际项目中pom.xml依赖写法: <dependency> <groupId>org.springf
- RestTemplate简介Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTem
- 自定义log4j日志文件命名规则项目中的日志需要采用一致的命名规范和文件规范,命名规则为:项目模块标识_index_日期时间_日志级别.lo
- ubuntu 安装jdk 的两种方法总结:1:通过ppa(源) 方式安装.2:通过官网下载安装包安装.这里推荐第1种,因为可以通过 apt-
- 问题 webView调用JS出错。 class TestJS {&n
- 何为系统APP何为三方APP?位于system分区内的是系统软件,位于data分区得的是第三方后安装的软件系统软件是指控制和协调计算机及外部
- 以下图中TV VOD两个按键为例,文章中所涉及到的文件只写文件名,因每个方案的路径各不相同,请自行全局搜索文件。 1.获取按键的扫
- 本文实例总结了C#实现启用与禁用本地网络的方式。分享给大家供大家参考,具体如下:1) 使用Hnetcfg.dll使用Add Referenc
- 本文实例为大家分享了opencv利用视频的前n帧求平均图像的具体代码,供大家参考,具体内容如下自己写的哈,可以用该小程序对视频求解平均模型。