[JAVA] Component和Configuration注解区别实例详解

2127 2
Honkers 2022-11-6 11:04:56 | 显示全部楼层 |阅读模式
目录

    引言
      AnnotationBean.javaAnnotationTest.javaSpring-source-5.2.8 两个注解声明增强逻辑



引言

第一眼看到这个题目,我相信大家都会脑子里面弹出来一个想法:这不都是 Spring 的注解么,加了这两个注解的类都会被最终封装成 BeanDefinition 交给 Spring 管理,能有什么区别?
首先先给大家看一段示例代码:

AnnotationBean.java
  1. import lombok.Data;
  2. import org.springframework.beans.factory.annotation.Qualifier;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. //@Configuration
  8. public class AnnotationBean {
  9.   @Qualifier("innerBean1")
  10.   @Bean()
  11.   public InnerBean innerBean1() {
  12.     return new InnerBean();
  13.   }
  14.   @Bean
  15.   public InnerBeanFactory innerBeanFactory() {
  16.     InnerBeanFactory factory = new InnerBeanFactory();
  17.     fctory.setInnerBean(innerBean1());
  18.     return factory;
  19.   }
  20.   public static class InnerBean {
  21.   }
  22.   @Data
  23.   public static class InnerBeanFactory {
  24.     private InnerBean innerBean;
  25.   }
  26. }
复制代码
AnnotationTest.java
  1. @Test
  2. void test7() {
  3.   AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BASE_PACKAGE);
  4.   Object bean1 = applicationContext.getBean("innerBean1");
  5.   Object factoryBean = applicationContext.getBean("innerBeanFactory");
  6.   int hashCode1 = bean1.hashCode();
  7.   InnerBean innerBeanViaFactory = ((InnerBeanFactory) factoryBean).getInnerBean();
  8.   int hashCode2 = innerBeanViaFactory.hashCode();
  9.   Assertions.assertEquals(hashCode1, hashCode2);
  10. }
复制代码
大家可以先猜猜看,这个test7()的执行结果究竟是成功呢还是失败呢?
答案是失败的。如果将AnnotationBean的注解从 @Component 换成 @Configuration,那test7()就会执行成功。
究竟是为什么呢?通常 Spring 管理的 bean 不都是单例的么?
别急,让笔者慢慢道来 ~~~

Spring-source-5.2.8 两个注解声明

以下是摘自 Spring-source-5.2.8 的两个注解的声明
  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Indexed
  5. public @interface Component {
  6.     /**
  7.      * The value may indicate a suggestion for a logical component name,
  8.      * to be turned into a Spring bean in case of an autodetected component.
  9.      * @return the suggested component name, if any (or empty String otherwise)
  10.      */
  11.     String value() default "";
  12. }
  13. ---------------------------------- 这是分割线 -----------------------------------
  14. @Target(ElementType.TYPE)
  15. @Retention(RetentionPolicy.RUNTIME)
  16. @Documented
  17. @Component
  18. public @interface Configuration {
  19.     /**
  20.      * Explicitly specify the name of the Spring bean definition associated with the
  21.      * {@code @Configuration} class. If left unspecified (the common case), a bean
  22.      * name will be automatically generated.
  23.      * <p>The custom name applies only if the {@code @Configuration} class is picked
  24.      * up via component scanning or supplied directly to an
  25.      * {@link AnnotationConfigApplicationContext}. If the {@code @Configuration} class
  26.      * is registered as a traditional XML bean definition, the name/id of the bean
  27.      * element will take precedence.
  28.      * @return the explicit component name, if any (or empty String otherwise)
  29.      * @see AnnotationBeanNameGenerator
  30.      */
  31.     @AliasFor(annotation = Component.class)
  32.     String value() default "";
  33.     /**
  34.      * Specify whether {@code @Bean} methods should get proxied in order to enforce
  35.      * bean lifecycle behavior, e.g. to return shared singleton bean instances even
  36.      * in case of direct {@code @Bean} method calls in user code. This feature
  37.      * requires method interception, implemented through a runtime-generated CGLIB
  38.      * subclass which comes with limitations such as the configuration class and
  39.      * its methods not being allowed to declare {@code final}.
  40.      * <p>The default is {@code true}, allowing for 'inter-bean references' via direct
  41.      * method calls within the configuration class as well as for external calls to
  42.      * this configuration's {@code @Bean} methods, e.g. from another configuration class.
  43.      * If this is not needed since each of this particular configuration's {@code @Bean}
  44.      * methods is self-contained and designed as a plain factory method for container use,
  45.      * switch this flag to {@code false} in order to avoid CGLIB subclass processing.
  46.      * <p>Turning off bean method interception effectively processes {@code @Bean}
  47.      * methods individually like when declared on non-{@code @Configuration} classes,
  48.      * a.k.a. "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore
  49.      * behaviorally equivalent to removing the {@code @Configuration} stereotype.
  50.      * @since 5.2
  51.      */
  52.     boolean proxyBeanMethods() default true;
  53. }
复制代码
从这两个注解的定义中,可能大家已经看出了一点端倪:@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
  1. Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
  2. if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
  3.   beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
  4. }
  5. else if (config != null || isConfigurationCandidate(metadata)) {
  6.   beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
  7. }
复制代码
默认情况下,Spring 在将带有 @Configuration 注解的类封装成 BeanDefinition 的时候,会设置一个属性 CONFIGURATION_CLASS_ATTRIBUTE,属性值为 CONFIGURATION_CLASS_FULL, 反之,如果只有 @Component 注解,那该属性值就会是 CONFIGURATION_CLASS_LITE (这个属性值很重要). 在 @Component 注解的调用过程当中,有下面一段逻辑:
org.springframework.context.annotation.ConfigurationClassPostProcessor#enhanceConfigurationClasses
  1. for (String beanName : beanFactory.getBeanDefinitionNames()) {
  2.   ......
  3.   if ((configClassAttr != null || methodMetadata != null) && beanDef instanceof AbstractBeanDefinition) {
  4.     ......
  5.     if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
  6.       if (!(beanDef instanceof AbstractBeanDefinition)) {
  7.         throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
  8.                             beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
  9.       }
  10.       else if (logger.isInfoEnabled() && beanFactory.containsSingleton(beanName)) {
  11.         logger.info("Cannot enhance @Configuration bean definition '" + beanName +
  12.             "' since its singleton instance has been created too early. The typical cause " +
  13.             "is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
  14.             "return type: Consider declaring such methods as 'static'.");
  15.       }
  16.       configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
  17.     }
  18.   }
  19. }
  20. if (configBeanDefs.isEmpty()) {
  21.   // nothing to enhance -> return immediately
  22.   return;
  23. }
  24. ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
  25. ......
复制代码
如果 BeanDefinition 的 ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE 属性值为 ConfigurationClassUtils.CONFIGURATION_CLASS_FULL, 则该 BeanDefinition 对象会被加入到 Map<String, AbstractBeanDefinition> configBeanDefs 容器中。
如果 Spring 发现该 Map 是空的,则认为不需要进行代理增强,立即返回;反之,则为该类 (本文中,被代理类即为 AnnotationBean, 以下简称该类) 创建代理。
所以如果该类的注解是 @Component,调用带有 @Bean 注解的 innerBean1() 方法时,this 对象为 Spring 容器中的真实单例对象,例如 AnnotationBean@4149.
  1. @Bean
  2. public InnerBeanFactory innerBeanFactory() {
  3.   InnerBeanFactory factory = new InnerBeanFactory();
  4.   factory.setInnerBean(innerBean1());
  5.   return factory;
  6. }
复制代码
那在上述方法中每调用一次 innerBean1() 方法时,势必会返回一个新创建的 InnerBean 对象。如果该类的注解为 @Configuration 时,this 对象为 Spring 生成的 AnnotationBean 的代理对象,例如 AnnotationBean$$EnhancerBySpringCGLIB$$90f8540c@4296,

增强逻辑
  1. // The callbacks to use. Note that these callbacks must be stateless.
  2. private static final Callback[] CALLBACKS = new Callback[] {
  3.   new BeanMethodInterceptor(),
  4.   new BeanFactoryAwareMethodInterceptor(),
  5.   NoOp.INSTANCE
  6. };
  7. ----------------------------------- 这是分割线 -------------------------------
  8. /**
  9.   * Creates a new CGLIB {@link Enhancer} instance.
  10.   */
  11.   private Enhancer newEnhancer(Class<?> configSuperClass, @Nullable ClassLoader classLoader) {
  12.     Enhancer enhancer = new Enhancer();
  13.     enhancer.setSuperclass(configSuperClass);
  14.     enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
  15.     enhancer.setUseFactory(false);
  16.     enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
  17.     enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
  18.     enhancer.setCallbackFilter(CALLBACK_FILTER);
  19.     enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
  20.     return enhancer;
  21. }
复制代码
当在上述方法中调用 innerBean1() 时,ConfigurationClassEnhancer 遍历 3 种回调方法判断当前调用应该使用哪个回调方法时,第一个回调类型匹配成功org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#isMatch 匹配过程如下所示:
  1. @Override
  2. public boolean isMatch(Method candidateMethod) {
  3.   return (candidateMethod.getDeclaringClass() != Object.class && !BeanFactoryAwareMethodInterceptor.isSetBeanFactory(candidateMethod) && BeanAnnotationHelper.isBeanAnnotated(candidateMethod));
  4. }
复制代码
匹配成功之后,使用 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
  1. Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) : beanFactory.getBean(beanName));
复制代码
看到这里,相信大家和笔者一样,对 @Component 和 @Configuration 注解的区别豁然开朗:
默认情况下,带有 @Configuration 的类在被 Spring 解析时,会使用切面进行字节码增强,在解析带有 @Bean的方法 innerBeanFactory() 时,该方法内部显式调用了另一个带有 @Bean 注解的方法 innerBean1(), 那么返回的对象和 Spring 第一次解析带有 @Bean 注解的方法 innerBean1() 生成的单例对象是同一个.
以上就是Component和Configuration注解区别实例详解的详细内容,更多关于Component Configuration区别的资料请关注中国红客联盟其它相关文章!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4008
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行