Inverse of @DependsOn annotation

不打扰是莪最后的温柔 提交于 2019-12-12 14:12:46

问题


Spring (and presumably other DI containers, but I'm using Spring) recognises the @DependsOn annotation. You use this to identify any other beans that must be initiated BEFORE this bean, eg

@Component
@DependsOn({"initiatedFirst", "initiatedSecond"})
public class InitiatedThird {

//...

Is there an analogous annotation that means that the supplied beans must be initiated AFTER the annotated bean? For example

@Component
@DependencyOf({"initiatedSecond", "initiatedThird"})
public class InitiatedFirst {

//...

I would have thought this would be quite a common use case for when you don't have access to the source / initialisation of a bean but want to configure some other beans beforehand. Does such an annotation exist?


回答1:


No, but if you don't have access to code, you still can use xml

<bean id="initiatedSecond" class="..." depends-on="initiatedFirst" />
<bean id="initiateThird" class="..." depends-on="initiatedSecond" />

and so on...

Edit

Other option is to use a BeanFactoryPostProcessor to add the dependences via BeanDefiniton.setDependsOn(String[]).

For example (Not tested)

public class DependencyConfigurer implements BeanFactoryPostProcessor {

    private Map<String, String[]> dependencies = new HashMap<String, String[]>();

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : dependencies.keySet()) {
            BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
            bd.setDependsOn(dependencies.get(beanName));
        }

    }

    public Map<String, String[]> getDependencies() {
        return dependencies;
    }

    public void setDependencies(Map<String, String[]> dependencies) {
        this.dependencies = dependencies;
    }

}

Another option is to make a well know early instantiated bean to depends on your bean. (seems ugly but will work).

Finally you could override AbstractApplicationContext.onRefresh() and instantiate your beans.



来源:https://stackoverflow.com/questions/16295526/inverse-of-dependson-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!