Issue
How can I inject a Spring bean in class that implements org.flywaydb.core.api.migration.JavaMigration
?
It seems it's been added in Flyway 6.0: This issue seems to talk about it, but I don't really see how to proceed.
I've also seen this answer which seems to talk about it, but I was hoping there was a shorter solution (I don't have the requirement about the JPA dependency that the author speaks about).
Thanks
Solution
Assuming you are using Spring Boot:
- First you will need to disable the initialization and triggering of flyway by setting the
spring.flyway.enabled
tofalse
. This also means you will have to configure Flyway yourself. - Annotate your
JavaMigrations
classes with@Component
. - Create a Class that implements
CommandLineRunner
and implements the run method. This class should also have yourJavaMigrations
autowired and your datasource url, user and password will also need to be injected as well or alternatively aDataSource
object. In the
run
method collect yourJavaMigrations
objects into an array and programmatically register them with Flyway and then run the migration:JavaMigrations migrations[] = {myJavaMigration}; Flyway flyway = Flyway.configure() .dataSource(url, user, password) .javaMigrations(migrations) .load(); flyway.migrate();
Full implementation:
@Component
public class MyJavaMigration extends BaseJavaMigration {
...
}
@Component
public class MyFlywayMigration implements CommandLineRunner {
@Autowired
private MyJavaMigration myJavaMigration;
@Autowired
private DataSource dataSource;
@Override
public void run(String... args) {
JavaMigrations migrations[] = {myJavaMigration};
Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.javaMigrations(migrations)
.load();
flyway.migrate();
}
}
Answered By - Dean
Answer Checked By - Clifford M. (JavaFixing Volunteer)