I'm trying to inject component of configuration properties in the flyway migration java code but it always null.
I'm using spring boot with Flyway.
@Component
@ConfigurationProperties(prefix = "code")
public class CodesProp {
private String codePath;
}
Then inside Flyway migration code, trying to autowrire this component as following:
public class V1_4__Migrate_codes_metadata implements SpringJdbcMigration {
@Autowired
private CodesProp codesProp ;
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
codesProp.getCodePath();
}
Here, codesProp is always null.
Is there any way to inject spring beans inside flyway or make it initialized before flyway bean?
Thank You.
If you are using deltaspike you can use BeanProvider to get a reference to your Class. Here is a DAO example, but it should work fine with your class too.
Change your DAO code:
Then in your migration method:
And there you've got your reference.
(referenced from: Flyway Migration with java)
Flyway doesn't support dependency injection into
SpringJdbcMigration
implementations. It simply looks for classes on the classpath that implementSpringJdbcMigration
and creates a new instance using the default constructor. This is performed in SpringJdbcMigrationResolver. When the migration is executed, SpringJdbcMigrationExecutor creates a newJdbcTemplate
and then calls your migration implementation'smigrate
method.If you really need dependencies to be injected into your Java-based migrations, I think you'll have to implement your own
MigrationResolver
that retrieves beans of a particular type from the application context and creates and returns aResolvedMigration
instance for each.If like me, you don't want to wait for Flyway 4.1, you can use Flyway 4.0 and add the following to your Spring Boot application:
1) Create a
ApplicationContextAwareSpringJdbcMigrationResolver
class in your project:2) Add a new configuration class to post process the Spring Boot generated Flyway instance:
Note that I have some hardcoded dependencies on tomcat jdbc pool, h2 and mysql. If you are using something else, you will need to change the code there (If there is anybody that knows how to avoid it, please comment!)
Also note that the
@ComponentScan
package needs to match with where you will put the Java migration classes.Also note that I had to add the
SqlMigrationResolver
back in since I want to support both the SQL and the Java flavor of the migrations.3) Create a Java class in the
db.migrations
package that does the actual migration:Note that you need to make the class a
@Component
and it needs to implement theSpringJdbcMigration
. In this class, you can use Spring constructor injection for any Spring bean from your context you might need to do the migration(s).Note: Be sure to disable ddl validation of Hibernate, because the validation seems to run before Flyway runs: