Search code examples
springspring-bootflyway

Spring beans are not injected in flyway java based migration


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.


Solution

  • Flyway doesn't support dependency injection into SpringJdbcMigration implementations. It simply looks for classes on the classpath that implement SpringJdbcMigration and creates a new instance using the default constructor. This is performed in SpringJdbcMigrationResolver. When the migration is executed, SpringJdbcMigrationExecutor creates a new JdbcTemplate and then calls your migration implementation's migrate 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 a ResolvedMigration instance for each.