Spring @Configuration 和 @Component 區別
一句話概括就是 @Configuration 中所有帶 @Bean 注解的方法都會被動態代理,因此調用該方法返回的都是同一個實例。
下面看看實現的細節。
1 @Configuration 注解: 2 @Target(ElementType.TYPE) 3 @Retention(RetentionPolicy.RUNTIME) 4 @Documented 5 @Component 6 public @interface Configuration { 7 String value() default ""; 8 }
從定義來看, @Configuration 注解本質上還是 @Component,因此 <context:component-scan/> 或者 @ComponentScan 都能處理@Configuration 注解的類。
@Configuration 標記的類必須符合下面的要求:
配置類必須以類的形式提供(不能是工廠方法返回的實例),允許通過生成子類在運行時增強(cglib 動態代理)。
配置類不能是 final 類(沒法動態代理)。
配置注解通常為了通過 @Bean 注解生成 Spring 容器管理的類,
配置類必須是非本地的(即不能在方法中聲明,不能是 private)。
任何嵌套配置類都必須聲明為static。
@Bean 方法可能不會反過來創建進一步的配置類(也就是返回的 bean 如果帶有 @Configuration,也不會被特殊處理,只會作為普通的 bean)。
加載過程
Spring 容器在啟動時,會加載默認的一些 PostPRocessor,其中就有 ConfigurationClassPostProcessor,這個后置處理程序專門處理帶有 @Configuration 注解的類,這個程序會在 bean 定義加載完成后,在 bean 初始化前進行處理。主要處理的過程就是使用 cglib 動態代理增強類,而且是對其中帶有 @Bean 注解的方法進行處理。
在 ConfigurationClassPostProcessor 中的 postProcessBeanFactory 方法中調用了下面的方法:
1 /** 2 * Post-processes a BeanFactory in search of Configuration class BeanDefinitions; 3 * any candidates are then enhanced by a {@link ConfigurationClassEnhancer}. 4 * Candidate status is determined by BeanDefinition attribute metadata. 5 * @see ConfigurationClassEnhancer 6 */ 7 public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) { 8 Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<String, AbstractBeanDefinition>(); 9 for (String beanName : beanFactory.getBeanDefinitionNames()) { 10 BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName); 11 if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) { 12 //省略部分代碼 13 configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef); 14 } 15 } 16 if (configBeanDefs.isEmpty()) { 17 // nothing to enhance -> return immediately 18 return; 19 } 20 ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer(); 21 for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) { 22 AbstractBeanDefinition beanDef = entry.getValue(); 23 // If a @Configuration class gets proxied, always proxy the target class 24 beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); 25 try { 26 // Set enhanced subclass of the user-specified bean class 27 Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader); 28 Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader); 29 if (configClass != enhancedClass) { 30 //省略部分代碼 31 beanDef.setBeanClass(enhancedClass); 32 } 33 } 34 catch (Throwable ex) { 35 throw new IllegalStateException( 36 "Cannot load configuration class: " + beanDef.getBeanClassName(), ex); 37 } 38 } 39 }
在方法的第一次循環中,查找到所有帶有 @Configuration 注解的 bean 定義,然后在第二個 for 循環中,通過下面的方法對類進行增強:
1 Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
然后使用增強后的類替換了原有的 beanClass:
1 beanDef.setBeanClass(enhancedClass);
所以到此時,所有帶有 @Configuration 注解的 bean 都已經變成了增強的類。
下面關注上面的 enhance 增強方法,多跟一步就能看到下面的方法:
1 /** 2 * Creates a new CGLIB {@link Enhancer} instance. 3 */ 4 private Enhancer newEnhancer(Class<?> superclass, ClassLoader classLoader) { 5 Enhancer enhancer = new Enhancer(); 6 enhancer.setSuperclass(superclass); 7 enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class}); 8 enhancer.setUseFactory(false); 9 enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); 10 enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader)); 11 enhancer.setCallbackFilter(CALLBACK_FILTER); 12 enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes()); 13 return enhancer; 14 }
通過 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 8 private static final ConditionalCallbackFilter CALLBACK_FILTER = 9 new ConditionalCallbackFilter(CALLBACKS);
其中 BeanMethodInterceptor 匹配方法如下:
1 @Override 2 public boolean isMatch(Method candidateMethod) { 3 return BeanAnnotationHelper.isBeanAnnotated(candidateMethod); 4 } 5 6 //BeanAnnotationHelper 7 public static boolean isBeanAnnotated(Method method) { 8 return AnnotatedElementUtils.hasAnnotation(method, Bean.class); 9 }
也就是當方法有 @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 4 @Bean 5 public Country country(){ 6 return new Country(); 7 } 8 9 @Bean 10 public UserInfo userInfo(){ 11 return new UserInfo(country()); 12 } 13 14 }
相信大多數人第一次看到上面 userInfo() 中調用 country() 時,會認為這里的 Country 和上面 @Bean 方法返回的 Country 可能不是同一個對象,因此可能會通過下面的方式來替代這種方式:
1 @Autowired 2 private Country country;
實際上不需要這么做(后面會給出需要這樣做的場景),直接調用 country() 方法返回的是同一個實例。
下面看調用 country() 和 userInfo() 方法時的邏輯。
現在我們已經知道 @Configuration 注解的類是如何被處理的了,現在關注上面的 BeanMethodInterceptor,看看帶有 @Bean 注解的方法執行的邏輯。下面分解來看 intercept 方法。
1 //首先通過反射從增強的 Configuration 注解類中獲取 beanFactory 2 ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance); 3 4 //然后通過方法獲取 beanName,默認為方法名,可以通過 @Bean 注解指定 5 String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod); 6 7 //確定這個 bean 是否指定了代理的范圍 8 //默認下面 if 條件 false 不會執行 9 Scope scope = AnnotatedElementUtils.findMergedAnnotation(beanMethod, Scope.class); 10 if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) { 11 String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName); 12 if (beanFactory.isCurrentlyInCreation(scopedBeanName)) { 13 beanName = scopedBeanName; 14 } 15 } 16 17 //中間跳過一段 Factorybean 相關代碼 18 19 //判斷當前執行的方法是否為正在執行的 @Bean 方法 20 //因為存在在 userInfo() 方法中調用 country() 方法 21 //如果 country() 也有 @Bean 注解,那么這個返回值就是 false. 22 if (isCurrentlyInvokedFactoryMethod(beanMethod)) { 23 // 判斷返回值類型,如果是 BeanFactoryPostProcessor 就寫警告日志 24 if (logger.isWarnEnabled() && 25 BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) { 26 logger.warn(String.format( 27 "@Bean method %s.%s is non-static and returns an object " + 28 "assignable to Spring's BeanFactoryPostProcessor interface. This will " + 29 "result in a failure to process annotations such as @Autowired, " + 30 "@Resource and @PostConstruct within the method's declaring " + 31 "@Configuration class. Add the 'static' modifier to this method to avoid " + 32 "these container lifecycle issues; see @Bean javadoc for complete details.", 33 beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName())); 34 } 35 //直接調用原方法創建 bean 36 return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs); 37 } 38 //如果不滿足上面 if,也就是在 userInfo() 中調用的 country() 方法 39 return obtainBeanInstanceFromFactory(beanMethod, beanMethodArgs, beanFactory, beanName);
關於 isCurrentlyInvokedFactoryMethod 方法
可以參考 SimpleInstantiationStrategy 中的 instantiate 方法,這里先設置的調用方法:
1 currentlyInvokedFactoryMethod.set(factoryMethod); 2 return factoryMethod.invoke(factoryBean, args);
而通過方法內部直接調用 country() 方法時,不走上面的邏輯,直接進的代理方法,也就是當前的 intercept方法,因此當前的工廠方法和執行的方法就不相同了。
obtainBeanInstanceFromFactory 方法比較簡單,就是通過 beanFactory.getBean 獲取 Country,如果已經創建了就會直接返回,如果沒有執行過,就會通過 invokeSuper 首次執行。
因此我們在 @Configuration 注解定義的 bean 方法中可以直接調用方法,不需要 @Autowired 注入后使用。
@Component 注意
@Component 注解並沒有通過 cglib 來代理@Bean 方法的調用,因此像下面這樣配置時,就是兩個不同的 country。
1 @Component 2 public class MyBeanConfig { 3 4 @Bean 5 public Country country(){ 6 return new Country(); 7 } 8 9 @Bean 10 public UserInfo userInfo(){ 11 return new UserInfo(country()); 12 } 13 14 }
有些特殊情況下,我們不希望 MyBeanConfig 被代理(代理后會變成WebMvcConfig$$EnhancerBySpringCGLIB$$8bef3235293)時,就得用 @Component,這種情況下,上面的寫法就需要改成下面這樣:
1 @Component 2 public class MyBeanConfig { 3 4 @Autowired 5 private Country country; 6 7 @Bean 8 public Country country(){ 9 return new Country(); 10 } 11 12 @Bean 13 public UserInfo userInfo(){ 14 return new UserInfo(country); 15 } 16 17 }
這種方式可以保證使用的同一個 Country 實例。