引言

第一眼看到这个题目,我相信大家都会脑子里面弹出来一个想法:这不都是 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() 生成的单例对象是同一个.

以上就是Component和Configuration注解区别实例详解的详细内容,更多关于Component Configuration区别的资料请关注Devmax其它相关文章!

Component和Configuration注解区别实例详解的更多相关文章

  1. 一种angular的方法级的缓存注解(装饰器)

    本篇文章主要介绍了一种angular的方法级的缓存注解(装饰器),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Spring详细讲解@Autowired注解

    @Autowired注解可以用在类属性,构造函数,setter方法和函数参数上,该注解可以准确地控制bean在何处如何自动装配的过程。在默认情况下,该注解是类型驱动的注入

  3. js中值类型和引用类型的区别介绍

    这篇文章介绍了js中值类型和引用类型的区别,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  4. 详解springboot测试类注解

    这篇文章主要介绍了springboot测试类注解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. @FeignClient注解中属性contextId的使用说明

    这篇文章主要介绍了@FeignClient注解中属性contextId的使用说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  6. PHP中$GLOBALS与global的区别详解

    今天小编就为大家分享一篇关于PHP中$GLOBALS与global的区别详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  7. jQuery和AngularJS的区别浅析

    这篇文章主要介绍了jQuery和AngularJS的区别浅析,本文着重讲解一个熟悉jQuery开的程序员如何应对AngularJS中的一些编程思想的转变,需要的朋友可以参考下

  8. Java泛型与注解全面分析讲解

    Java 泛型(generics)是 Jdk 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。Annotation(注解)是JDK1.5及以后版本引入的。它可以用于创建文档,跟踪代码中的依赖性,甚至执行基本编译时检查。需要的可以参考一下

  9. Spring Boot 利用注解方式整合 MyBatis

    这篇文章主要介绍了Spring Boot 利用注解方式整合 MyBatis,文章围绕主主题的相关资料展开详细的内容介绍,需要的小伙伴可以参考一下

  10. SpringBoot底层注解超详细介绍

    这篇文章主要介绍了SpringBoot底层注解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部