执行某事.在创建bean之后或之前 [英] Execute sth. after or before bean is created

查看:131
本文介绍了执行某事.在创建bean之后或之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use spring-boot with flyway and a datasource, so both beans are automatically configured by spring-boot. Now I would like to execute foo(some code / a SQL script) either directly after the datasource or before the flyway bean is initialized.

我该如何在外部配置-最好使用批注-应该调用flywaydependsOn fooBean还是应该调用数据源foo的post构造?

How can I configure externally -preferably with annotations- that flyway dependsOn fooBean or that post construct of the datasource foo should be called?

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

Is it the 'better' approach trying to alter the bean initialization order or registering an ApplicationListener (if possible)?

推荐答案

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

I guess the only solution is to override the Flyway configuration and add the "clean" method call. So create your own FlywayConfig class like this:

@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;
    }
}

这篇关于执行某事.在创建bean之后或之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆