Spring中@DependsOn注解的使用
Spring中@DependsOn,主要是使用在类和方法上, 作用是当前对象要依赖另外一些对象,被依赖的对象会先注册到Spring的IOC容器中.
1 @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.
*
* <p>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.
*
* <p>May be used on any class directly or indirectly annotated with
* {@link org.springframework.stereotype.Component} or on methods annotated
* with {@link Bean}.
*
* <p>Using {@link DependsOn} at the class level has no effect unless component-scanning
* is being used. If a {@link DependsOn}-annotated class is declared via XML,
* {@link DependsOn} annotation metadata is ignored, and
* {@code <bean depends-on="..."/>} is respected instead.
*
* @author Juergen Hoeller
* @since 3.0
*/
@Target({
ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DependsOn {
String[] value() default {
};
}
说明:
- 1 使用范围. 注解可以使用在类上,方法上. 在类上,一般与@Component注解使用 ; 在方法上, 通常会与@Bean注解使用.
- 2 注解中的字段是一个数组value, 填充的是bean对象,可以放置多个bean, 填入的bean会比使用该注解的对象早一点注册到容器中.
使用场景:
在一些场景, 需要去监听事件源的触发,从而处理相应的业务. 那么就需要监听类比事件源先注册到容器中, 因为事件源触发前,监听就应该存在,否则就不满足使用场景的要求.
2 @DependsOn的使用
案例1
1 准备一个SpringBoot环境
2 添加监听类和事件源类
@Component
public class ASource {
public ASource(){
System.out.println("事件创建");
}
}
@Component
public class BListener {
public BListener(){
System.out.println("监听创建");
}
}
3 启动项目,查看控制台
// 事件创建
// 监听创建
上面明显,不符合实际使用要求.
4 改造事件源类
@Component
@DependsOn(value = {
"BListener"})
public class ASource {
public ASource(){
System.out.println("事件创建");
}
}
5 启动项目,查看控制台
// 监听创建
// 事件创建
上述输出,满足使用要求.
案例2
1 添加配置类
@Configuration
public class Config {
@Bean
@DependsOn(value = {
"BListener"})
public ASource aSource(){
return new ASource();
}
@Bean
public BListener bListener(){
return new BListener();
}
}
2 启动项目,查看控制台
// 监听创建
// 事件创建
满足使用要求.