我需要先初始化一个组件。使用@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知道BeanA的存在(例如,当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注释或像这样处理它的可能性?

最佳答案

我相信没有开箱即用的 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

10-07 21:03