Spring高級注解之@DependsOn詳解
官方文檔
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該注解的屬性是一個字符串數組,數組的元素是每個依賴的bean的名稱。
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DependsOn { String[] value() default {}; }
@DependsOn注解主要用于指定當前bean所依賴的beans。任何被指定依賴的bean都由Spring保證在當前bean之前創(chuàng)建。在少數情況下,bean不是通過屬性或構造函數參數顯式依賴于另一個bean,但卻需要要求另一個bean優(yōu)先完成初始化,則可以使用@DependsOn這個注解。
@DependsOn既可以指定初始化依賴順序,也可以指定bean相應的銷毀執(zhí)行順序(僅在單例bean的情況下)。
可用于任何直接或間接帶@Component注解的bean或在用@Bean注釋的方法上。 如果使用的是xml配置,則需要使用<bean dependens on=“…”/>標簽.
簡單描述就是@DependsOn可以控制bean的創(chuàng)建、初始化(InitializingBean)、銷毀方法執(zhí)行順序。
示例:假如有三個Bean類叫Aaa、Bbb、Ccc分別實現(xiàn)了如下兩個接口。org.springframework.beans.factory.InitializingBeanorg.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值,調用BeanDefinition#setDependsOn保存。 源碼見ClassPathBeanDefinitionScanner#doScan,AnnotationConfigUtils#processCommonDefinitionAnnotations(AnnotatedBeanDefinition, AnnotatedTypeMetadata)
創(chuàng)建bean時,也就是調用AbstractBeanFactory#doGetBean時,會獲取這些被依賴的beanName,按照數組順序,再調用AbstractBeanFactory#getBean(beanName)來優(yōu)先創(chuàng)建被依賴的bean,從而達到控制依賴順序。
除此之外,在創(chuàng)建bean時,還會調用AbstractBeanFactory#registerDisposableBeanIfNecessary來向Spring中注冊帶有銷毀方法的bean,源碼見DefaultSingletonBeanRegistry#registerDisposableBean,內部通過LinkedHashMap保存。key為bean名稱。進程退出時,會逆序調用銷毀方法。 源碼見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(); }
到此這篇關于Spring高級注解之@DependsOn詳解的文章就介紹到這了,更多相關@DependsOn詳解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Mybatis模糊查詢之三種定義參數方法和聚合查詢、主鍵回填實現(xiàn)方法
這篇文章主要介紹了Mybatis模糊查詢之三種定義參數方法和聚合查詢、主鍵回填實現(xiàn)方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03springboot實現(xiàn)的https單向認證和雙向認證(java生成證書)
springboot https單向認證和雙向認證,本文主要介紹了springboot實現(xiàn)的https單向認證和雙向認證,具有一定的參考價值,感興趣的可以了解一下2024-04-04Spring?security?oauth2以redis作為tokenstore及jackson序列化失敗問題
這篇文章主要介紹了Spring?security?oauth2以redis作為tokenstore及jackson序列化失敗問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教<BR>2024-04-04Mybatis-Plus之ID自動增長的設置實現(xiàn)
本文主要介紹了Mybatis-Plus之ID自動增長的設置實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07JAVA8 stream中三個參數的reduce方法對List進行分組統(tǒng)計操作
這篇文章主要介紹了JAVA8 stream中三個參數的reduce方法對List進行分組統(tǒng)計操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08