Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 861
NHS Avatar asked Jan 21 '16 12:01

NHS


People also ask

How do you inject beans in spring core?

In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation.

How does Flyway migration work?

Flyway works by checking the current version of the database and by applying new migrations automatically before the rest of the application starts.

Does Flyway migrate data?

Overview. With Flyway all changes to the database are called migrations. Migrations can be either versioned or repeatable. Versioned migrations come in 2 forms: regular and undo.


1 Answers

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.

like image 156
Andy Wilkinson Avatar answered Sep 20 '22 18:09

Andy Wilkinson