使用数据库迁移时,我显然希望在运行迁移之前没有任何 DAO 可用。
目前我正在声明很多DAO,它们都有一个depends-on=databaseMigrator属性。我觉得这很麻烦,尤其是因为它很容易出错。
有没有更紧凑的方法来做到这一点?
笔记:
depend-on成为迁移器。您可以尝试编写一个实现BeanFactoryPostProcessor接口的类来自动为您注册依赖项:
警告:该类尚未编译。
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将此类 Bean 与所有其他 Bean 一起包含在内。
<bean class="DatabaseMigratorDependencyResolver"/>
Run Code Online (Sandbox Code Playgroud)
Spring 将在开始启动其余 Bean 之前自动运行它。