Spring @Configuration 和 @Component 区别

x33g5p2x  于2021-12-03 转载在 Spring  
字(6.9k)|赞(0)|评价(0)|浏览(365)

Spring @Configuration 和 @Component 区别

下面看看实现的细节。

@Configuration 注解:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Component
  5. public @interface Configuration {
  6. String value() default "";
  7. }

从定义来看, @Configuration 注解本质上还是 @Component,因此 `` 或者 @ComponentScan 都能处理@Configuration 注解的类。

@Configuration 标记的类必须符合下面的要求:

  • 配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。
  • 配置类不能是 final 类(没法动态代理)。
  • 配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类,
  • 配置类必须是非本地的(即不能在方法中声明,不能是 private)。
  • 任何嵌套配置类都必须声明为static
  • @Bean 方法可能不会反过来创建进一步的配置类(也就是返回的 bean 如果带有 @Configuration,也不会被特殊处理,只会作为普通的 bean)。

加载过程

Spring 容器在启动时,会加载默认的一些 PostPRocessor,其中就有 ConfigurationClassPostProcessor,这个后置处理程序专门处理带有 @Configuration 注解的类,这个程序会在 bean 定义加载完成后,在 bean 初始化前进行处理。主要处理的过程就是使用 cglib 动态代理增强类,而且是对其中带有 @Bean 注解的方法进行处理。

ConfigurationClassPostProcessor 中的 postProcessBeanFactory 方法中调用了下面的方法:

  1. /** * Post-processes a BeanFactory in search of Configuration class BeanDefinitions; * any candidates are then enhanced by a {@link ConfigurationClassEnhancer}. * Candidate status is determined by BeanDefinition attribute metadata. * @see ConfigurationClassEnhancer */
  2. public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
  3. Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<String, AbstractBeanDefinition>();
  4. for (String beanName : beanFactory.getBeanDefinitionNames()) {
  5. BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
  6. if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
  7. //省略部分代码
  8. configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
  9. }
  10. }
  11. if (configBeanDefs.isEmpty()) {
  12. // nothing to enhance -> return immediately
  13. return;
  14. }
  15. ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
  16. for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
  17. AbstractBeanDefinition beanDef = entry.getValue();
  18. // If a @Configuration class gets proxied, always proxy the target class
  19. beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
  20. try {
  21. // Set enhanced subclass of the user-specified bean class
  22. Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
  23. Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
  24. if (configClass != enhancedClass) {
  25. //省略部分代码
  26. beanDef.setBeanClass(enhancedClass);
  27. }
  28. }
  29. catch (Throwable ex) {
  30. throw new IllegalStateException(
  31. "Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
  32. }
  33. }
  34. }

在方法的第一次循环中,查找到所有带有 @Configuration 注解的 bean 定义,然后在第二个 for 循环中,通过下面的方法对类进行增强:

  1. Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);

然后使用增强后的类替换了原有的 beanClass

  1. beanDef.setBeanClass(enhancedClass);

所以到此时,所有带有 @Configuration 注解的 bean 都已经变成了增强的类。

下面关注上面的 enhance 增强方法,多跟一步就能看到下面的方法:

  1. /** * Creates a new CGLIB {@link Enhancer} instance. */
  2. private Enhancer newEnhancer(Class<?> superclass, ClassLoader classLoader) {
  3. Enhancer enhancer = new Enhancer();
  4. enhancer.setSuperclass(superclass);
  5. enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
  6. enhancer.setUseFactory(false);
  7. enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
  8. enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
  9. enhancer.setCallbackFilter(CALLBACK_FILTER);
  10. enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
  11. return enhancer;
  12. }

通过 cglib 代理的类在调用方法时,会通过 CallbackFilter 调用,这里的 CALLBACK_FILTER 如下:

  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. private static final ConditionalCallbackFilter CALLBACK_FILTER =
  8. new ConditionalCallbackFilter(CALLBACKS);

其中 BeanMethodInterceptor 匹配方法如下:

  1. @Override
  2. public boolean isMatch(Method candidateMethod) {
  3. return BeanAnnotationHelper.isBeanAnnotated(candidateMethod);
  4. }
  5. //BeanAnnotationHelper
  6. public static boolean isBeanAnnotated(Method method) {
  7. return AnnotatedElementUtils.hasAnnotation(method, Bean.class);
  8. }

也就是当方法有 @Bean 注解的时候,就会执行这个回调方法。

另一个 BeanFactoryAwareMethodInterceptor 匹配的方法如下:

  1. @Override
  2. public boolean isMatch(Method candidateMethod) {
  3. return (candidateMethod.getName().equals("setBeanFactory") &&
  4. candidateMethod.getParameterTypes().length == 1 &&
  5. BeanFactory.class == candidateMethod.getParameterTypes()[0] &&
  6. BeanFactoryAware.class.isAssignableFrom(candidateMethod.getDeclaringClass()));
  7. }

当前类还需要实现 BeanFactoryAware 接口,上面的 isMatch 就是匹配的这个接口的方法。

@Bean 注解方法执行策略

先给一个简单的示例代码:

  1. @Configuration
  2. public class MyBeanConfig {
  3. @Bean
  4. public Country country(){
  5. return new Country();
  6. }
  7. @Bean
  8. public UserInfo userInfo(){
  9. return new UserInfo(country());
  10. }
  11. }

现在我们已经知道 @Configuration 注解的类是如何被处理的了,现在关注上面的 BeanMethodInterceptor,看看带有 @Bean 注解的方法执行的逻辑。下面分解来看 intercept 方法。

  1. //首先通过反射从增强的 Configuration 注解类中获取 beanFactory
  2. ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
  3. //然后通过方法获取 beanName,默认为方法名,可以通过 @Bean 注解指定
  4. String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);
  5. //确定这个 bean 是否指定了代理的范围
  6. //默认下面 if 条件 false 不会执行
  7. Scope scope = AnnotatedElementUtils.findMergedAnnotation(beanMethod, Scope.class);
  8. if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
  9. String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
  10. if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
  11. beanName = scopedBeanName;
  12. }
  13. }
  14. //中间跳过一段 Factorybean 相关代码
  15. //判断当前执行的方法是否为正在执行的 @Bean 方法
  16. //因为存在在 userInfo() 方法中调用 country() 方法
  17. //如果 country() 也有 @Bean 注解,那么这个返回值就是 false.
  18. if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
  19. // 判断返回值类型,如果是 BeanFactoryPostProcessor 就写警告日志
  20. if (logger.isWarnEnabled() &&
  21. BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
  22. logger.warn(String.format(
  23. "@Bean method %s.%s is non-static and returns an object " +
  24. "assignable to Spring's BeanFactoryPostProcessor interface. This will " +
  25. "result in a failure to process annotations such as @Autowired, " +
  26. "@Resource and @PostConstruct within the method's declaring " +
  27. "@Configuration class. Add the 'static' modifier to this method to avoid " +
  28. "these container lifecycle issues; see @Bean javadoc for complete details.",
  29. beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
  30. }
  31. //直接调用原方法创建 bean
  32. return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
  33. }
  34. //如果不满足上面 if,也就是在 userInfo() 中调用的 country() 方法
  35. return obtainBeanInstanceFromFactory(beanMethod, beanMethodArgs, beanFactory, beanName);
  1. currentlyInvokedFactoryMethod.set(factoryMethod);
  2. return factoryMethod.invoke(factoryBean, args);12

obtainBeanInstanceFromFactory 方法比较简单,就是通过 beanFactory.getBean 获取 Country,如果已经创建了就会直接返回,如果没有执行过,就会通过 invokeSuper 首次执行。

因此我们在 @Configuration 注解定义的 bean 方法中可以直接调用方法,不需要 @Autowired 注入后使用。

@Component 注意

@Component 注解并没有通过 cglib 来代理@Bean 方法的调用,因此像下面这样配置时,就是两个不同的 country。

  1. @Component
  2. public class MyBeanConfig {
  3. @Bean
  4. public Country country(){
  5. return new Country();
  6. }
  7. @Bean
  8. public UserInfo userInfo(){
  9. return new UserInfo(country());
  10. }
  11. }

有些特殊情况下,我们不希望 MyBeanConfig 被代理(代理后会变成WebMvcConfig$$EnhancerBySpringCGLIB$$8bef3235293)时,就得用 @Component,这种情况下,上面的写法就需要改成下面这样:

  1. @Component
  2. public class MyBeanConfig {
  3. @Autowired
  4. private Country country;
  5. @Bean
  6. public Country country(){
  7. return new Country();
  8. }
  9. @Bean
  10. public UserInfo userInfo(){
  11. return new UserInfo(country);
  12. }
  13. }

这种方式可以保证使用的同一个 Country 实例。

相关文章