问题
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