在liquibase CustomTaskChange类中使用其他spring bean

Seb*_*mer 6 java spring liquibase

我需要做一些数据迁移,这在liquibase变更集中太复杂了.我们用春天

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

到目前为止一切都很好.

我的问题是: 是否可以从这样的类中访问其他spring bean?

当我尝试在这个类中使用一个自动装配的bean时,它是null,这让我觉得现在根本没有完成自动装配?

我还在其他一些帖子中读到,必须在所有其他bean之前初始化Liquibase 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();
    }
...
Run Code Online (Sandbox Code Playgroud)

我得到一个异常,在调试时我可以看到someBean为null.

这是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;
}
...
Run Code Online (Sandbox Code Playgroud)

更多配置:

<?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>
Run Code Online (Sandbox Code Playgroud)

这里是变更集的调用:

<?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>
Run Code Online (Sandbox Code Playgroud)

vin*_*nce 7

我目前也在解决这个问题...经过几个小时的挖掘,我找到了 2 个解决方案,不需要 AOP。

液体库版本:4.1.1


方案A

官方给出的customChange示例中

https://docs.liquibase.com/change-types/community/custom-change.html

在CustomChange.setFileOpener中,ResourceAccessor实际上是一个内部类SpringLiquibase$SpringResourceOpener,它有一个成员'resourceLoader',它确实是一个ApplicationContext。不幸的是,它是私有的并且没有可用的吸气剂。

所以这里出现了一个丑陋的解决方案:使用反射来获取它并调用 getBean


方案B(更优雅)

在开始之前,让我们先了解一些有关 Liquibase 的基本事实。将 Liquibase 与 Spring Boot 集成的官方方法是使用:

org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration

这是一个条件内部配置 bean,仅当 SpringLiquibase.class 丢失时才用于创建 SpringLiquibase

@Configuration
@ConditionalOnMissingBean(SpringLiquibase.class)
@EnableConfigurationProperties({ DataSourceProperties.class,
        LiquibaseProperties.class })
@Import(LiquibaseJpaDependencyConfiguration.class)
public static class LiquibaseConfiguration {...}
Run Code Online (Sandbox Code Playgroud)

因此我们可以通过添加 liquibase 配置 bean 来创建我们自己的 SpringLiquibase

@Getter
@Configuration
@EnableConfigurationProperties(LiquibaseProperties.class)
public class LiquibaseConfig {

    private DataSource dataSource;

    private LiquibaseProperties properties;

    public LiquibaseConfig(DataSource dataSource, LiquibaseProperties properties) {
        this.dataSource = dataSource;
        this.properties = properties;
    }

    @Bean
    public SpringLiquibase liquibase() {
        SpringLiquibase liquibase = new BeanAwareSpringLiquibase();
        liquibase.setDataSource(dataSource);
        liquibase.setChangeLog(this.properties.getChangeLog());
        liquibase.setContexts(this.properties.getContexts());
        liquibase.setDefaultSchema(this.properties.getDefaultSchema());
        liquibase.setDropFirst(this.properties.isDropFirst());
        liquibase.setShouldRun(this.properties.isEnabled());
        liquibase.setLabels(this.properties.getLabels());
        liquibase.setChangeLogParameters(this.properties.getParameters());
        liquibase.setRollbackFile(this.properties.getRollbackFile());
        return liquibase;
   }
}
Run Code Online (Sandbox Code Playgroud)

在其中我们新建一个SpringLiquibase的扩展类:BeanAwareSpringLiquibase

public class BeanAwareSpringLiquibase extends SpringLiquibase {
private static ResourceLoader applicationContext;

public BeanAwareSpringLiquibase() {
}

public static final <T> T getBean(Class<T> beanClass) throws Exception {
    if (ApplicationContext.class.isInstance(applicationContext)) {
        return ((ApplicationContext)applicationContext).getBean(beanClass);
    } else {
        throw new Exception("Resource loader is not an instance of ApplicationContext");
    }
}

public static final <T> T getBean(String beanName) throws Exception {
    if (ApplicationContext.class.isInstance(applicationContext)) {
        return ((ApplicationContext)applicationContext).getBean(beanName);
    } else {
        throw new Exception("Resource loader is not an instance of ApplicationContext");
    }
}

@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
    super.setResourceLoader(resourceLoader);
    applicationContext = resourceLoader;
}}
Run Code Online (Sandbox Code Playgroud)

BeanAwareSpringLiquibase 有一个对前面提到的 ResourceLoader 的静态引用。在Spring Bootstartup上,ResourceLoaderAware接口定义的setResourceLoader会在InitializingBean接口定义的afterPropertiesSet之前自动调用,代码执行如下:

  1. Spring Boot调用setResourceLoader,将resourceLoader(applicationContext)注入到BeanAwareSpringLiquibase。

  2. Spring Boot 调用 afterPropertiesSet,执行 Liquibase 更新,包括 customChange,现在您已经拥有对 applicationContext 的完全访问权限

附:

  1. 请记住将您的 Liquibase 配置 bean 包路径添加到 @ComponentScan,否则它仍然会使用 LiquibaseAutoConfiguration 而不是我们自己的 LiquibaseConfig。

  2. 在“执行”之前准备好“setUp”中所需的所有 bean 是一个更好的约定。


Rol*_*der 4

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

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