@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是否存在:是