@DependsOn

@DependsOn注解用于指定当前组件依赖的其他组件,确保被依赖的组件在IOC容器中先注册。当注解在类上时,常与@Component一起用于类级别的依赖;在方法上则与@Bean结合,确保方法生成的bean在依赖的bean之后初始化。如果依赖的bean不存在,启动时会抛出错误。示例展示了在不同情况下的使用效果和结果。
摘要由CSDN通过智能技术生成

@DependsOn

@DependsOn : 当前组件依赖于另一个组件,被依赖的组件需要先注册到IOC容器中

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DependsOn {

    String[] value() default {};

}

当作用在类上时,通常会与@Component及其衍生注解等注解配合使用
当作用在方法上时,通常会与@Bean注解配合使用

示例

作用在类上

  • 依赖bean不存在
@DependsOn("demoB")
@Component
@Slf4j
public class DemoA implements InitializingBean {
    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        final Object demoB = applicationContext.getBean("demoB");
        log.info("DemoB是否存在:{}", demoB == null ? "否" : "是");
    }
}

启动报错:A component required a bean named 'demoB' that could not be found

  • 依赖bean对象存在

增加依赖类DeomB

@Component
public class DemoB {
}

打印结果: DemoB是否存在:是

作用在方法上

  • 依赖bean不存在
@Slf4j
public class DemoC implements InitializingBean {
    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        final Object demoD = applicationContext.getBean("demoD");
        log.info("DemoD是否存在:{}", demoD == null ? "否" : "是");
    }
}
@Configuration
public class Config {

    @DependsOn("demoD")
    @Bean
    public DemoC demoC() {
        return new DemoC();
    }
}

启动报错:A component required a bean named 'demoD' that could not be found

  • 依赖bean对象存在
@Configuration
public class Config {

    @DependsOn("demoD")
    @Bean
    public DemoC demoC() {
        return new DemoC();
    }

    @Bean
    public DemoD demoD() {
        return new DemoD();
    }
}

打印结果: DemoD是否存在:是

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值