Component和Configuration注解區(qū)別實(shí)例詳解
引言
第一眼看到這個(gè)題目,我相信大家都會(huì)腦子里面彈出來一個(gè)想法:這不都是 Spring 的注解么,加了這兩個(gè)注解的類都會(huì)被最終封裝成 BeanDefinition 交給 Spring 管理,能有什么區(qū)別?
首先先給大家看一段示例代碼:
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); }
大家可以先猜猜看,這個(gè)test7()的執(zhí)行結(jié)果究竟是成功呢還是失敗呢?
答案是失敗的。如果將AnnotationBean的注解從 @Component 換成 @Configuration,那test7()就會(huì)執(zhí)行成功。
究竟是為什么呢?通常 Spring 管理的 bean 不都是單例的么?
別急,讓筆者慢慢道來 ~~~
Spring-source-5.2.8 兩個(gè)注解聲明
以下是摘自 Spring-source-5.2.8 的兩個(gè)注解的聲明
@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; }
從這兩個(gè)注解的定義中,可能大家已經(jīng)看出了一點(diǎn)端倪:@Configuration 比 @Component 多一個(gè)成員變量 boolean proxyBeanMethods()
默認(rèn)值是 true. 從這個(gè)成員變量的注釋中,我們可以看到一句話
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.
其實(shí)從這句話,我們就可以初步得到我們想要的答案了:在帶有 @Configuration 注解的類中,一個(gè)帶有 @Bean 注解的方法顯式調(diào)用另一個(gè)帶有 @Bean 注解的方法,返回的是共享的單例對象. 下面我們從 Spring 源碼實(shí)現(xiàn)角度來看看這中間的原理.
從 Spring 源碼實(shí)現(xiàn)中可以得出一個(gè)規(guī)律,Spring 作者在實(shí)現(xiàn)注解時(shí),通常是先收集解析,再調(diào)用。@Configuration是 基于 @Component 實(shí)現(xiàn)的,在 @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); }
默認(rèn)情況下,Spring 在將帶有 @Configuration 注解的類封裝成 BeanDefinition 的時(shí)候,會(huì)設(shè)置一個(gè)屬性 CONFIGURATION_CLASS_ATTRIBUTE
,屬性值為 CONFIGURATION_CLASS_FULL
, 反之,如果只有 @Component 注解,那該屬性值就會(huì)是 CONFIGURATION_CLASS_LITE
(這個(gè)屬性值很重要). 在 @Component 注解的調(diào)用過程當(dāng)中,有下面一段邏輯:
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 對象會(huì)被加入到 Map<String, AbstractBeanDefinition> configBeanDefs
容器中。
如果 Spring 發(fā)現(xiàn)該 Map 是空的,則認(rèn)為不需要進(jìn)行代理增強(qiáng),立即返回;反之,則為該類 (本文中,被代理類即為 AnnotationBean, 以下簡稱該類) 創(chuàng)建代理。
所以如果該類的注解是 @Component,調(diào)用帶有 @Bean 注解的 innerBean1() 方法時(shí),this 對象為 Spring 容器中的真實(shí)單例對象,例如 AnnotationBean@4149
.
@Bean public InnerBeanFactory innerBeanFactory() { InnerBeanFactory factory = new InnerBeanFactory(); factory.setInnerBean(innerBean1()); return factory; }
那在上述方法中每調(diào)用一次 innerBean1() 方法時(shí),勢必會(huì)返回一個(gè)新創(chuàng)建的 InnerBean 對象。如果該類的注解為 @Configuration 時(shí),this 對象為 Spring 生成的 AnnotationBean 的代理對象,例如 AnnotationBean$$EnhancerBySpringCGLIB$$90f8540c@4296
,
增強(qiáng)邏輯
// 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; }
當(dāng)在上述方法中調(diào)用 innerBean1() 時(shí),ConfigurationClassEnhancer 遍歷 3 種回調(diào)方法判斷當(dāng)前調(diào)用應(yīng)該使用哪個(gè)回調(diào)方法時(shí),第一個(gè)回調(diào)類型匹配成功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() 方法調(diào)用進(jìn)行攔截. 在本例中,innerBean1() 被增強(qiáng)器調(diào)用了兩次,第一次調(diào)用是 Spring 解析帶有 @Bean 注解的 innerBean1() 方法,將構(gòu)造的 InnerBean 對象加入 Spring 單例池中. 第二次調(diào)用是 Spring 解析帶有 @Bean 注解的 innerBeanFactory() 方法,在該方法中顯式調(diào)用 innerBean1(). 在第二次調(diào)用時(shí),增強(qiáng)過程如下所示:org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#resolveBeanReference
Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) : beanFactory.getBean(beanName));
看到這里,相信大家和筆者一樣,對 @Component 和 @Configuration 注解的區(qū)別豁然開朗:
默認(rèn)情況下,帶有 @Configuration 的類在被 Spring 解析時(shí),會(huì)使用切面進(jìn)行字節(jié)碼增強(qiáng),在解析帶有 @Bean的方法 innerBeanFactory() 時(shí),該方法內(nèi)部顯式調(diào)用了另一個(gè)帶有 @Bean 注解的方法 innerBean1(), 那么返回的對象和 Spring 第一次解析帶有 @Bean 注解的方法 innerBean1() 生成的單例對象是同一個(gè).
以上就是Component和Configuration注解區(qū)別實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Component Configuration區(qū)別的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
springboot 多數(shù)據(jù)源配置不生效遇到的坑及解決
這篇文章主要介紹了springboot 多數(shù)據(jù)源配置不生效遇到的坑及解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11解決spring懶加載以及@PostConstruct結(jié)合的坑
這篇文章主要介紹了解決spring懶加載以及@PostConstruct結(jié)合的坑,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Kafka多節(jié)點(diǎn)分布式集群搭建實(shí)現(xiàn)過程詳解
這篇文章主要介紹了Kafka多節(jié)點(diǎn)分布式集群搭建實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Mybatis?Plus?QueryWrapper復(fù)合用法詳解
這篇文章主要介紹了Mybatis?Plus?QueryWrapper復(fù)合用法詳解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。2022-01-01xxl-job定時(shí)任務(wù)配置應(yīng)用及添加到springboot項(xiàng)目中實(shí)現(xiàn)動(dòng)態(tài)API調(diào)用
XXL-JOB是一個(gè)分布式任務(wù)調(diào)度平臺(tái),其核心設(shè)計(jì)目標(biāo)是開發(fā)迅速、學(xué)習(xí)簡單、輕量級(jí)、易擴(kuò)展,本篇文章主要是對xuxueli的xxl-job做一個(gè)簡單的配置,以及將其添加到自己已有的項(xiàng)目中進(jìn)行api調(diào)用,感興趣的朋友跟隨小編一起看看吧2024-04-04Spring項(xiàng)目運(yùn)行依賴spring-contex解析
這篇文章主要介紹了Spring項(xiàng)目運(yùn)行依賴spring-contex解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05SpringBoot請求處理之常用參數(shù)注解介紹與源碼分析
SpringBoot是一種整合Spring技術(shù)棧的方式(或者說是框架),同時(shí)也是簡化Spring的一種快速開發(fā)的腳手架,本篇讓我們一起學(xué)習(xí)請求處理、常用注解和方法參數(shù)的小技巧2022-10-10SpringSecurity實(shí)現(xiàn)前后端分離的示例詳解
Spring Security默認(rèn)提供賬號(hào)密碼認(rèn)證方式,具體實(shí)現(xiàn)是在UsernamePasswordAuthenticationFilter 中,這篇文章主要介紹了SpringSecurity實(shí)現(xiàn)前后端分離的示例詳解,需要的朋友可以參考下2023-03-03