3

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

BobJI
  • 163
  • 1
  • 9

1 Answers1

3

Assuming you are using Spring Boot:

  1. First you will need to disable the initialization and triggering of flyway by setting the spring.flyway.enabled to false. This also means you will have to configure Flyway yourself.
  2. Annotate your JavaMigrations classes with @Component.
  3. Create a Class that implements CommandLineRunner and implements the run method. This class should also have your JavaMigrations autowired and your datasource url, user and password will also need to be injected as well or alternatively a DataSource object.
  4. In the run method collect your JavaMigrations 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();
    }
}
Dean
  • 1,833
  • 10
  • 28
  • You don't need to turn `spring.flyway.enabled` =`false`. The above code can be simplified to just `Flyway.configure().javaMigrations(myJavaMigration).load()` as long as you have `myJavaMigration` in your class path. – guneetgstar Dec 14 '20 at 02:10