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 启动项目,查看控制台

// 监听创建
// 事件创建

满足使用要求.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值