Spring中@DependsOn注解的作用及實現(xiàn)原理解析
本文給大家講解Spring中@DependsOn注解的作用及實現(xiàn)原理!
官方文檔解釋
Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization.
A depends-on declaration can specify both an initialization-time dependency and, in the case of singleton beans only, a corresponding destruction-time dependency. Dependent beans that define a depends-on relationship with a given bean are destroyed first, prior to the given bean itself being destroyed. Thus, a depends-on declaration can also control shutdown order.
May be used on any class directly or indirectly annotated with org.springframework.stereotype.Component or on methods annotated with Bean.
Using DependsOn at the class level has no effect unless component-scanning is being used. If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored, and <bean depends-on="..."/> is respected instead.
@DependsOn注解的作用
org.springframework.context.annotation.DependsOn
該注解的屬性是一個字符串?dāng)?shù)組,數(shù)組的元素是每個依賴的bean的名稱。
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DependsOn { String[] value() default {}; }
@DependsOn
注解主要用于指定當(dāng)前bean所依賴的beans。任何被指定依賴的bean都由Spring保證在當(dāng)前bean之前創(chuàng)建。在少數(shù)情況下,bean不是通過屬性或構(gòu)造函數(shù)參數(shù)顯式依賴于另一個bean,但卻需要要求另一個bean優(yōu)先完成初始化,則可以使用@DependsOn
這個注解。
@DependsOn
既可以指定初始化依賴順序,也可以指定bean相應(yīng)的銷毀執(zhí)行順序(僅在單例bean的情況下)。
可用于任何直接或間接帶@Component
注解的bean或在用@Bean
注釋的方法上。
如果使用的是xml配置,則需要使用<bean dependens on=“…”/>
標(biāo)簽.
簡單描述就是@DependsOn
可以控制bean的創(chuàng)建、初始化(InitializingBean)、銷毀方法執(zhí)行順序。
示例:假如有三個Bean類叫Aaa、Bbb、Ccc分別實現(xiàn)了如下兩個接口。
org.springframework.beans.factory.InitializingBean
org.springframework.beans.factory.DisposableBean
Ccc通過@DependsOn指定依賴bean創(chuàng)建的順序為Bbb > Aaa
@DependsOn({"bbb","ccc"}) @Service public class Aaa implements InitializingBean, DisposableBean { private static final Logger logger = LoggerFactory.getLogger(Aaa.class); public Aaa() { logger.info(this.getClass().getName() + " Construction"); } @Override public void afterPropertiesSet() throws Exception { logger.info(this.getClass().getName() + " afterPropertiesSet"); } @Override public void destroy() throws Exception { logger.info(this.getClass().getName() + " destroy"); } }
Bbb Ccc類實現(xiàn)如下
@Service public class Bbb implements InitializingBean, DisposableBean { //實現(xiàn)和Aaa相同 } @Service public class Ccc implements InitializingBean, DisposableBean { //實現(xiàn)和Aaa相同 }
那么初始順序如下: bbb --> ccc --> aaa
而銷毀方法執(zhí)行順序正好相反如下: aaa --> ccc --> bbb
@DependsOn注解的實現(xiàn)原理
Spring在啟動時掃描到一個bean,會封裝成一個BeanDefinition,如果是AnnotatedBeanDefinition
則解析類上的注解信息,發(fā)現(xiàn)@DependsOn
注解,則讀取value值,調(diào)用BeanDefinition#setDependsOn
保存。
源碼見ClassPathBeanDefinitionScanner#doScan
,AnnotationConfigUtils#processCommonDefinitionAnnotations(AnnotatedBeanDefinition, AnnotatedTypeMetadata)
創(chuàng)建bean時,也就是調(diào)用AbstractBeanFactory#doGetBean
時,會獲取這些被依賴的beanName,按照數(shù)組順序,再調(diào)用AbstractBeanFactory#getBean(beanName)
來優(yōu)先創(chuàng)建被依賴的bean,從而達(dá)到控制依賴順序。
除此之外,在創(chuàng)建bean時,還會調(diào)用AbstractBeanFactory#registerDisposableBeanIfNecessary
來向Spring中注冊帶有銷毀方法的bean,源碼見DefaultSingletonBeanRegistry#registerDisposableBean
,內(nèi)部通過LinkedHashMap保存。key為bean名稱。進(jìn)程退出時,會逆序調(diào)用銷毀方法。
源碼見DefaultSingletonBeanRegistry#destroySingletons
public void destroySingletons() { if (logger.isTraceEnabled()) { logger.trace("Destroying singletons in " + this); } synchronized (this.singletonObjects) { this.singletonsCurrentlyInDestruction = true; } String[] disposableBeanNames; synchronized (this.disposableBeans) { disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet()); } for (int i = disposableBeanNames.length - 1; i >= 0; i--) { destroySingleton(disposableBeanNames[i]); } this.containedBeanMap.clear(); this.dependentBeanMap.clear(); this.dependenciesForBeanMap.clear(); clearSingletonCache(); }
到此這篇關(guān)于Spring中@DependsOn注解的作用及實現(xiàn)原理解析的文章就介紹到這了,更多相關(guān)Spring中@DependsOn注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java EasyExcel導(dǎo)出報內(nèi)存溢出的解決辦法
使用EasyExcel進(jìn)行大數(shù)據(jù)量導(dǎo)出時容易導(dǎo)致內(nèi)存溢出,特別是在導(dǎo)出百萬級別的數(shù)據(jù)時,你有遇到過這種情況嗎,以下是小編整理的解決該問題的一些常見方法,需要的朋友可以參考下2024-10-10Spring?Boot獲取resources目錄下的文件三種方式詳解
在Spring?Boot項目中,經(jīng)常需要獲取resources目錄下的文件,這些文件可以包括配置文件、模板文件、靜態(tài)資源等,這篇文章主要介紹了Spring?Boot獲取resources目錄下的文件的三種方式,需要的朋友可以參考下2023-06-06關(guān)于idea-web.xml版本過低怎么生成新的(web.xml報錯)問題
今天通過本文給大家分享idea-web.xml版本過低怎么生成新的(web.xml報錯)問題,通過更換web.xml版本解決此問題,感興趣的朋友跟隨小編一起看看吧2021-07-07