执行某事在bean创建之后或之前

时间:2015-04-20 11:00:10

标签: spring initialization spring-boot

我将spring-boot与flyway和数据源一起使用,因此两个bean都是由spring-boot自动配置的。现在我想直接在数据源之后或者在初始化flyway bean之前执行foo(一些代码/一个SQL脚本)。

我如何在外部配置 - 最好是带注释 - flyway依赖于fooBean还是应该调用数据源foo的post构造?

尝试更改bean初始化顺序或注册ApplicationListener(如果可能)是“更好”的方法吗?

1 个答案:

答案 0 :(得分:2)

我想唯一的解决方案是覆盖Flyway配置并添加" clean"方法调用。因此,像这样创建自己的FlywayConfig类:

@Configuration
public class FlywayConfig {

    @Autowired
    private FlywayProperties properties = new FlywayProperties();

    @Autowired(required = false)
    @FlywayDataSource
    private DataSource flywayDataSource;

    @Autowired(required = false)
    private DataSource dataSource;

    @Bean(initMethod = "migrate")
    public Flyway flyway() {
        Flyway flyway = new Flyway();
        if (this.properties.isCreateDataSource()) {
            flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(),
                    this.properties.getPassword(), this.properties.getInitSqls()
                            .toArray(new String[0]));
        }
        else if (this.flywayDataSource != null) {
            flyway.setDataSource(this.flywayDataSource);
        }
        else {
            flyway.setDataSource(this.dataSource);
        }
        flyway.clean(); // <-- this drops the schema
        return flyway;
    }
}