Reputation: 467
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?
Upvotes: 3
Views: 2192
Reputation: 438
Adding to the answer of @Stuck (lombok optional of course).
@Configuration
@RequiredArgsConstructor
public class FlywayConfiguration implements FlywayConfigurationCustomizer {
final JavaMigration[] migrations;
@Override
public void customize(FluentConfiguration configuration) {
configuration.javaMigrations(migrations);
}
}
Upvotes: 0
Reputation: 12292
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);
}
}
Upvotes: 7