Component和Configuration注解區別實例詳解_第1頁
Component和Configuration注解區別實例詳解_第2頁
Component和Configuration注解區別實例詳解_第3頁
Component和Configuration注解區別實例詳解_第4頁
Component和Configuration注解區別實例詳解_第5頁
已閱讀5頁,還剩6頁未讀, 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

第Component和Configuration注解區別實例詳解目錄引言AnnotationBean.javaAnnotationTest.javaSpring-source-5.2.8兩個注解聲明增強邏輯

引言

第一眼看到這個題目,我相信大家都會腦子里面彈出來一個想法:這不都是Spring的注解么,加了這兩個注解的類都會被最終封裝成BeanDefinition交給Spring管理,能有什么區別?

首先先給大家看一段示例代碼:

AnnotationBean.java

importlombok.Data;

importorg.springframework.beans.factory.annotation.Qualifier;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importorg.springframework.stereotype.Component;

@Component

//@Configuration

publicclassAnnotationBean{

@Qualifier("innerBean1")

@Bean()

publicInnerBeaninnerBean1(){

returnnewInnerBean();

@Bean

publicInnerBeanFactoryinnerBeanFactory(){

InnerBeanFactoryfactory=newInnerBeanFactory();

factory.setInnerBean(innerBean1());

returnfactory;

publicstaticclassInnerBean{

@Data

publicstaticclassInnerBeanFactory{

privateInnerBeaninnerBean;

}

AnnotationTest.java

@Test

voidtest7(){

AnnotationConfigApplicationContextapplicationContext=newAnnotationConfigApplicationContext(BASE_PACKAGE);

Objectbean1=applicationContext.getBean("innerBean1");

ObjectfactoryBean=applicationContext.getBean("innerBeanFactory");

inthashCode1=bean1.hashCode();

InnerBeaninnerBeanViaFactory=((InnerBeanFactory)factoryBean).getInnerBean();

inthashCode2=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@interfaceComponent{

*Thevaluemayindicateasuggestionforalogicalcomponentname,

*tobeturnedintoaSpringbeanincaseofanautodetectedcomponent.

*@returnthesuggestedcomponentname,ifany(oremptyStringotherwise)

Stringvalue()default"";

----------------------------------這是分割線-----------------------------------

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Component

public@interfaceConfiguration{

*ExplicitlyspecifythenameoftheSpringbeandefinitionassociatedwiththe

*{@code@Configuration}class.Ifleftunspecified(thecommoncase),abean

*namewillbeautomaticallygenerated.

*pThecustomnameappliesonlyifthe{@code@Configuration}classispicked

*upviacomponentscanningorsupplieddirectlytoan

*{@linkAnnotationConfigApplicationContext}.Ifthe{@code@Configuration}class

*isregisteredasatraditionalXMLbeandefinition,thename/idofthebean

*elementwilltakeprecedence.

*@returntheexplicitcomponentname,ifany(oremptyStringotherwise)

*@seeAnnotationBeanNameGenerator

@AliasFor(annotation=Component.class)

Stringvalue()default"";

*Specifywhether{@code@Bean}methodsshouldgetproxiedinordertoenforce

*beanlifecyclebehavior,e.g.toreturnsharedsingletonbeaninstanceseven

*incaseofdirect{@code@Bean}methodcallsinusercode.Thisfeature

*requiresmethodinterception,implementedthrougharuntime-generatedCGLIB

*subclasswhichcomeswithlimitationssuchastheconfigurationclassand

*itsmethodsnotbeingallowedtodeclare{@codefinal}.

*pThedefaultis{@codetrue},allowingfor'inter-beanreferences'viadirect

*methodcallswithintheconfigurationclassaswellasforexternalcallsto

*thisconfiguration's{@code@Bean}methods,e.g.fromanotherconfigurationclass.

*Ifthisisnotneededsinceeachofthisparticularconfiguration's{@code@Bean}

*methodsisself-containedanddesignedasaplainfactorymethodforcontaineruse,

*switchthisflagto{@codefalse}inordertoavoidCGLIBsubclassprocessing.

*pTurningoffbeanmethodinterceptioneffectivelyprocesses{@code@Bean}

*methodsindividuallylikewhendeclaredonnon-{@code@Configuration}classes,

*a.k.a."@BeanLiteMode"(see{@linkBean@Bean'sjavadoc}).Itistherefore

*behaviorallyequivalenttoremovingthe{@code@Configuration}stereotype.

*@since5.2

booleanproxyBeanMethods()defaulttrue;

}

從這兩個注解的定義中,可能大家已經看出了一點端倪:@Configuration比@Component多一個成員變量booleanproxyBeanMethods()默認值是true.從這個成員變量的注釋中,我們可以看到一句話

Specifywhether{@code@Bean}methodsshouldgetproxiedinordertoenforcebeanlifecyclebehavior,e.g.toreturnsharedsingletonbeaninstancesevenincaseofdirect{@code@Bean}methodcallsinusercode.

其實從這句話,我們就可以初步得到我們想要的答案了:在帶有@Configuration注解的類中,一個帶有@Bean注解的方法顯式調用另一個帶有@Bean注解的方法,返回的是共享的單例對象.下面我們從Spring源碼實現角度來看看這中間的原理.

從Spring源碼實現中可以得出一個規律,Spring作者在實現注解時,通常是先收集解析,再調用。@Configuration是基于@Component實現的,在@Component的解析過程中,我們可以看到下面一段邏輯:

org.springframework.context.annotation.ConfigurationClassUtils#checkConfigurationClassCandidate

MapString,Objectconfig=metadata.getAnnotationAttributes(Configuration.class.getName());

if(config!=null!Boolean.FALSE.equals(config.get("proxyBeanMethods"))){

beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE,CONFIGURATION_CLASS_FULL);

elseif(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(StringbeanName:beanFactory.getBeanDefinitionNames()){

......

if((configClassAttr!=null||methodMetadata!=null)beanDefinstanceofAbstractBeanDefinition){

......

if(ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)){

if(!(beanDefinstanceofAbstractBeanDefinition)){

thrownewBeanDefinitionStoreException("Cannotenhance@Configurationbeandefinition'"+

beanName+"'sinceitisnotstoredinanAbstractBeanDefinitionsubclass");

elseif(logger.isInfoEnabled()beanFactory.containsSingleton(beanName)){

("Cannotenhance@Configurationbeandefinition'"+beanName+

"'sinceitssingletoninstancehasbeencreatedtooearly.Thetypicalcause"+

"isanon-static@BeanmethodwithaBeanDefinitionRegistryPostProcessor"+

"returntype:Considerdeclaringsuchmethodsas'static'.");

configBeanDefs.put(beanName,(AbstractBeanDefinition)beanDef);

if(configBeanDefs.isEmpty()){

//nothingtoenhance-returnimmediately

return;

ConfigurationClassEnhancerenhancer=newConfigurationClassEnhancer();

......

如果BeanDefinition的ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE屬性值為ConfigurationClassUtils.CONFIGURATION_CLASS_FULL,則該BeanDefinition對象會被加入到MapString,AbstractBeanDefinitionconfigBeanDefs容器中。

如果Spring發現該Map是空的,則認為不需要進行代理增強,立即返回;反之,則為該類(本文中,被代理類即為AnnotationBean,以下簡稱該類)創建代理。

所以如果該類的注解是@Component,調用帶有@Bean注解的innerBean1()方法時,this對象為Spring容器中的真實單例對象,例如AnnotationBean@4149.

@Bean

publicInnerBeanFactoryinnerBeanFactory(){

InnerBeanFactoryfactory=newInnerBeanFactory();

factory.setInnerBean(innerBean1());

returnfactory;

}

那在上述方法中每調用一次innerBean1()方法時,勢必會返回一個新創建的InnerBean對象。如果該類的注解為@Configuration時,this對象為Spring生成的AnnotationBean的代理對象,例如AnnotationBean$$EnhancerBySpringCGLIB$$90f8540c@4296,

增強邏輯

//Thecallbackstouse.Notethatthesecallbacksmustbestateless.

privatestaticfinalCallback[]CALLBACKS=newCallback[]{

newBeanMethodInterceptor(),

newBeanFactoryAwareMethodInterceptor(),

NoOp.INSTANCE

-----------------------------------這是分割線-------------------------------

*CreatesanewCGLIB{@linkEnhancer}instance.

privateEnhancernewEnhancer(ClassconfigSuperClass,@NullableClassLoaderclassLoader){

Enhancerenhancer=newEnhancer();

enhancer.setSuperclass(configSuperClass);

enhancer.setInterfaces(newClass[]{EnhancedConfiguration.class});

enhancer.setUseFactory(false);

enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);

enhancer.setStrategy(newBeanFactoryAwareGeneratorStrategy(classLoader));

enhancer.setCallbackFilter(CALLBACK_FILTER);

enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());

returnenhancer;

}

當在上述方法中調用innerBean1()時,ConfigurationClassEnhancer遍歷3種回調方法判斷當前調用應該使用哪個回調方法時,第一個回調類型匹配成功org.springframework.context.annotation.ConfigurationClassEnhancer.BeanMethodInterceptor#isMatch匹配過程如下所示:

@Override

publicbooleanisMatch(MethodcandidateMethod){

return(candidateMethod.getDeclaringClass()!=Object.class!BeanFactoryAwareMethodInterceptor.

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論