Spring中的@DependsOn注解
源碼:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DependsOn {
String[] value() default {};
}
作用:
作用:
用於指定某個類的創建依賴的bean對象先創建。spring中沒有特定bean的加載順序,使用此注解則可指定bean的加載順序。(在基於注解配置中,是按照類中方法的書寫順序決定的)
屬性:
value:
用於指定bean的唯一標識。被指定的bean會在當前bean創建之前加載。
使用場景:
在觀察者模式中,分為事件,事件源和監聽器。一般情況下,我們的監聽器負責監聽事件源,當事件源觸發了事件之后,監聽器就要捕獲,並且做出相應的處理。以此為前提,我們肯定希望監聽器的創建時間在事件源之前,此時就可以使用此注解。
1. 沒有用之前
代碼:
/**
* @author WGR
* @create 2020/9/16 -- 17:07
*/
@Component
public class CustomerA {
public CustomerA() {
System.out.println("事件源創建了。。。");
}
}
/**
* @author WGR
* @create 2020/9/16 -- 17:05
*/
@Component
public class CustomerListener {
public CustomerListener() {
System.out.println("監聽器創建了。。。");
}
}
public static void main(String[] args) {
//1.獲取容器
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext("com.dalianpai.spring5.dependon");
//2.根據id獲取對象
ac.start();
}
測試:

加載的順序是按照類名的來的
2.使用以后
/**
* @author WGR
* @create 2020/9/16 -- 17:07
*/
@Component
@DependsOn("customerListener")
public class CustomerA {
public CustomerA() {
System.out.println("事件源創建了。。。");
}
}

