使许多豆依赖一个豆的简短方法 [英] Short way of making many beans depend-on one bean
问题描述
使用数据库迁移时,我显然希望在运行迁移之前没有任何DAO可用.
When using database migrations, I obviously want none of the DAOs to be usable before the migrations are run.
此刻,我声明了很多 DAO,它们都具有depends-on=databaseMigrator
属性.我发现这很麻烦,尤其是因为它容易出错.
At the moment I'm declaring a lot of DAOs, all having a depends-on=databaseMigrator
property. I find this troubling, especially since it's error prone.
是否有更紧凑的方法?
注意:
- 依赖项属性不是从父bean继承"的;
- 我没有使用Hibernate或JPA,所以无法使sessionFactory bean
depend-on
成为迁移器.
- the depends-on attribute is not 'inherited' from parent beans;
- I am not using Hibernate or JPA so I can't make the sessionFactory bean
depend-on
the migrator.
推荐答案
You could try writing a class that implements the BeanFactoryPostProcessor interface to automatically register the dependencies for you:
警告::此类尚未编译.
public class DatabaseMigratorDependencyResolver implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
String[] beanNames = beanFactory.getBeanDefinitionNames();
for (String beanName : beanNames) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
// Your job is here:
// Feel free to make use of the methods available from the BeanDefinition class (http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/BeanDefinition.html)
boolean isDependentOnDatabaseMigrator = ...;
if (isDependentOnDatabaseMigrator) {
beanFactory.registerDependentBean("databaseMigrator", beanName);
}
}
}
}
然后,您可以在所有其他bean旁边包含该类的bean.
You could then include a bean of this class alongside all your other beans.
<bean class="DatabaseMigratorDependencyResolver"/>
Spring将在开始启动其余bean之前自动运行它.
Spring will automatically run it before it starts initiating the rest of the beans.
这篇关于使许多豆依赖一个豆的简短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!