Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way of making many beans depend-on one bean

Tags:

java

spring

When using database migrations, I obviously want none of the DAOs to be usable before the migrations are run.

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.

Is there a more compact way of doing this?


Notes:

  • 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.
like image 266
Robert Munteanu Avatar asked Jun 06 '09 12:06

Robert Munteanu


People also ask

How do I create multiple beans in the same class?

This can be achieved using the following steps: Creating a custom bean class and configuring it using the FactoryBean interface. Instantiating multiple beans of the same type using BeanFactoryPostProcessor interface.

What is the @bean annotation?

One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework.


1 Answers

You could try writing a class that implements the BeanFactoryPostProcessor interface to automatically register the dependencies for you:

Warning: This class has not been compiled.

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);
            }
        }
    }

}

You could then include a bean of this class alongside all your other beans.

<bean class="DatabaseMigratorDependencyResolver"/>

Spring will automatically run it before it starts initiating the rest of the beans.

like image 113
Adam Paynter Avatar answered Sep 20 '22 19:09

Adam Paynter