介绍
该注解用于声明当前bean依赖于另外一个bean。所依赖的bean
会被容器确保在当前bean
实例化之前被实例化。
使用
-
标注在带有@Component注解的类上面;
-
使用@DependsOn注解到类层面仅仅在使用@ComponentScan方式时才有效;
-
如果带有@DependsOn注解的类通过XML方式使用,该注解会被忽略;只有通过这种方式会生效;
-
-
标注在带有@Bean 注解的方法上面;。
@Component
public class ProducerService {
public ProducerService() {
System.out.println("ProducerService is creating");
}
}
@Component
@DependsOn(value = "producerService")
public class ConsumerService {
public ConsumerService() {
System.out.println("ConsumerService is creating");
}
}
@Bean
@Conditional(value = MyCondition.class)
@DependsOn("consumerService")
public OrderService orderService2() {
System.out.println("orderService is creating");
return new OrderService();
}
打印结果:
ProducerService is creating
ConsumerService is creating
orderService is creating