zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring中的@DependsOn注解

Spring 注解
2023-09-14 09:06:17 时间

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.没有用之前

@Component
public class CustomerA {
    public CustomerA() {
        System.out.println("事件源创建了。。。");
    }
}


@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.使用以后

image-20200916172543873