[英]Is there a “revert” to Spring @DependsOn annotation?
我需要在另一个组件之前初始化一个组件。 使用@DependsOn,它看起来像这样:
@Component("beana")
public class BeanA{
@PostConstruct
void init(){
// do smth
}
}
@Component("beanb")
@DependsOn("beana")
public class BeanB{
@PostConstruct
void init(){
// do smth
}
}
我现在必须告诉BeanB它取决于BeanA的初始化。 我的问题是我不希望BeanB知道BeanAs存在(例如,当BeanB在初始化时只在EventBus中发布事件并且BeanA处理这些事件时)。 我想在BeanA上使用一个注释,说它应该在BeanB之前初始化。 所以它会是这样的:
@Component("beana")
@RequiredBy("beanb")
public class BeanA{
@PostConstruct
void init(){
// do smth
}
}
@Component("beanb")
public class BeanB{
@PostConstruct
void init(){
// do smth
}
}
是否有任何Spring注释或可能性来处理它?
我相信没有开箱即用的弹簧注释,但你可以很容易地制作自己的。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RequiredBy {
String[] value();
}
然后可以遍历所有bean定义并将dependsOn设置为required
bean。
@Component
public static class RequiredByBeanDefinitionPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
for (String beanName : registry.getBeanDefinitionNames()) {
final BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
if (beanDefinition.getBeanClassName() == null) {
continue;
}
try {
final Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
if (beanClass.isAnnotationPresent(RequiredBy.class)) {
final String[] dependantBeanNames = beanClass.getAnnotation(RequiredBy.class).value();
for (String dependantBeanName : dependantBeanNames) {
BeanDefinition dependantBeanDefinition = registry.getBeanDefinition(dependantBeanName);
dependantBeanDefinition.setDependsOn(beanName);
}
}
}
catch (ClassNotFoundException e) { throw new RuntimeException(e); }
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { }
}
然后像你的例子一样使用它:
@Component("beanA")
public static class BeanA {
@PostConstruct
private void init() {
System.out.println(this.getClass().getSimpleName());
}
}
@Component("beanB")
@RequiredBy({ "beanC", "beanA" })
public static class BeanB {
@PostConstruct
private void init() {
System.out.println(this.getClass().getSimpleName());
}
}
@Component("beanC")
@RequiredBy("beanA")
public static class BeanC {
@PostConstruct
private void init() {
System.out.println(this.getClass().getSimpleName());
}
}
=>
BeanB
BeanC
BeanA
您可以按照pvpkiran的建议使用@Order注释。
您的代码看起来像这样:
@Component("beana")
@Order(1)
public class BeanA{
@PostConstruct
void init(){
// do smth
}
}
@Component("beanb")
@Order(2)
public class BeanB{
@PostConstruct
void init(){
// do smth
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.