Spring中的@DependsOn注解


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();
    }

測試:

image-20200916171653130

加載的順序是按照類名的來的

2.使用以后

/**
 * @author WGR
 * @create 2020/9/16 -- 17:07
 */
@Component
@DependsOn("customerListener")
public class CustomerA {
    public CustomerA() {
        System.out.println("事件源創建了。。。");
    }
}

image-20200916172543873


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM