2

I have seen many great workarounds to create Flyway JavaMigrations and injecting Spring Beans using @DependsOn and ApplicationContextAware (e.g. https://stackoverflow.com/a/48242865/5244937).

However a part of the Flyway 6 documentation claims Dependency Injection would be possible natively for Spring Beans:

Is is true? How would this work?

mararn1618
  • 437
  • 6
  • 16
  • By this line: ApplicationContext applicationContext = ...; // obtain a reference to Spring's ApplicationContext. – Simon Martinelli Jun 19 '20 at 08:37
  • Until now I have only used SQL based migrations and Flyways autodiscovery feature. Do I understand correctly that this will longer work with this approach and instead I need to .. - Manually kick off the migrations? - Use the pattern (1) Instantiate Spring Bean / FlywayMigrationInitializer, (2) Find the migrations manually using `.javaMigrations(..)` and (3) kick off flyway manually via `flyway.migrate();`? – mararn1618 Jun 19 '20 at 09:01
  • 1
    No SQL will still work and is IMHO the preferred way. – Simon Martinelli Jun 19 '20 at 09:25

1 Answers1

3

Mark your migrations as @Component and put them in a folder that is scanned by spring (e.g. within your application package and not in db.migrations). This will ensure @Autowired can be used because the bean is instantiated by spring. (The migrations in db.migrations will be scanned by flyway automatically and are not instantiated by spring.)

Then implement a FlywayConfigurationCustomizer to add the migrations by loading them from the spring context:

@Configuration
class FlywayConfiguration implements FlywayConfigurationCustomizer {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void customize(FluentConfiguration configuration) {
        JavaMigration[] migrationBeans = applicationContext
         .getBeansOfType(JavaMigration.class)
         .values().toArray(new JavaMigration[0]);
        configuration.javaMigrations(migrationBeans);
    }
}
Stuck
  • 11,225
  • 11
  • 59
  • 104