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:
depend-on
the migrator.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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With