java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > @DependsOn注解

Spring中@DependsOn注解的使用代码实例

作者:韩_师兄

这篇文章主要介绍了Spring中@DependsOn注解的使用代码实例,Spring中@DependsOn,主要是使用在类和方法上, 作用是当前对象要依赖另外一些对象,被依赖的对象会先注册到Spring的IOC容器中,需要的朋友可以参考下

@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 {};
}

说明

使用场景

在一些场景, 需要去监听事件源的触发,从而处理相应的业务. 那么就需要监听类比事件源先注册到容器中, 因为事件源触发前,监听就应该存在,否则就不满足使用场景的要求.

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

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

满足使用要求.

到此这篇关于Spring中@DependsOn注解的使用代码实例的文章就介绍到这了,更多相关@DependsOn注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文