在Liqubase CustomTaskChange类中使用其他Spring Bean类中、CustomTaskChange、Liqubase、Spring

2023-09-04 01:49:10 作者:玻璃娃娃

我需要执行一些数据迁移,这太复杂了,无法在Liquid Base变更集中完成。我们使用弹簧

这就是为什么我编写了一个实现liquibase.change.custom.CustomTaskChange类的类。然后,我从变更集中引用它。

下游商用车销量增速放缓 新业务处于培育期 中自科技去年净利由盈转亏

到目前为止一切都很好。

我的问题是: 是否可以从此类中访问其他Spring Bean?

当我尝试在这个类中使用自动连接的Bean时,它是空的,这让我认为自动连接在这一点上根本没有完成?

我还读到了其他一些线程,Liquibase Bean必须在所有其他Bean之前初始化,对吗?

以下是我编写的类的一个片段:

@Component
public class UpdateJob2 implements CustomTaskChange {

private String param1;

@Autowired
private SomeBean someBean;

@Override
public void execute(Database database) throws CustomChangeException {
    try {
        List<SomeObject> titleTypes = someBean.getSomeObjects(
                param1
        );
    } catch (Exception e) {         
        throw new CustomChangeException();
    }
...

我得到一个异常,调试时我可以看到某个Bean为空。

以下是SpringLiquibase的配置:

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@ComponentScan({
"xxx.xxx.."})
public class DatabaseConfiguration {

@Bean
public SpringLiquibase springLiquibase() {
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource());
    liquibase.setChangeLog("classpath:liquibase-changelog.xml");
    return liquibase;
}
...

更多配置:

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
     http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <includeAll path="dbschema"/>

</databaseChangeLog>

此处来自变更集的调用:

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
     http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

<changeSet id="201509281536" author="sr">
        <customChange class="xxx.xxx.xxx.UpdateJob2">
            <param name="param1" value="2" />
        </customChange>
</changeSet>

推荐答案

您的changeset.xml中引用的类不是由Spring托管的,因此像DI这样很酷的东西将无法工作。

您可以做的是将SpringBean注入到非Spring对象中。查看此答案:https://stackoverflow.com/a/1377740/4365460