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

原文地址:https://www.cnblogs.com/dalianpai/p/13680280.html