Component和Configuration注解区别实例详解

Java
240
0
0
2023-06-10
目录
  • 引言
  • AnnotationBean.java
  • AnnotationTest.java
  • Spring-source-5.2.8 两个注解声明
  • 增强逻辑

引言

第一眼看到这个题目,我相信大家都会脑子里面弹出来一个想法:这不都是 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("innerBean")
  @Bean()
  public InnerBean innerBean() {
    return new InnerBean();
  }
  @Bean
  public InnerBeanFactory innerBeanFactory() {
    InnerBeanFactory factory = new InnerBeanFactory();
    factory.setInnerBean(innerBean());
    return factory;
  }
  public static class InnerBean {
  }
  @Data
  public static class InnerBeanFactory {
    private InnerBean innerBean;
  }
}

AnnotationTest.java

@Test
void test() {
  AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BASE_PACKAGE);
  Object bean = applicationContext.getBean("innerBean1");
  Object factoryBean = applicationContext.getBean("innerBeanFactory");
  int hashCode = bean1.hashCode();
  InnerBean innerBeanViaFactory = ((InnerBeanFactory) factoryBean).getInnerBean();
  int hashCode = innerBeanViaFactory.hashCode();
  Assertions.assertEquals(hashCode, 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.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(innerBean());
  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() 生成的单例对象是同一个.