使许多豆依赖一个豆的简短方法 [英] Short way of making many beans depend-on one bean

查看:111
本文介绍了使许多豆依赖一个豆的简短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用数据库迁移时,我显然希望在运行迁移之前没有任何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.

是否有更紧凑的方法?

注意:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆