【问题标题】:creating schema with CommandLineRunner spring boot使用 CommandLineRunner spring boot 创建模式
【发布时间】:2019-07-02 14:30:45
【问题描述】:

在我的 Spring Boot 应用程序中,我正在使用 CommandLineRunner 创建一个新模式,然后它们会导入一些测试数据。

@Profile("create-schema")
@Component
public class CreateSchema {
    // creating schema inside. This works because I can see from the database
}

@Profile("import-data")
@Component
public class DataImporter {
}

这是application.properties中的序列

spring.profiles.active=${SPRING_PROFILE}, create-schema, import-data

并在 application.properties 中使用它

spring.jpa.properties.hibernate.default_schema=simba

架构创建在应用程序启动后开始;创建模式后,导入数据开始。

当导入数据运行时,我收到一个错误

关系schema_name.table_name 不存在

但是,一旦创建了架构并且我再次运行应用程序 - 它就可以工作了。所以,当我必须将我的应用程序部署到每次我必须创建一个模式来运行一些集成测试时——它会在那里失败。

我的运行顺序是否错误?

【问题讨论】:

  • 为什么在这里使用配置文件?
  • 没有具体原因,我在关注 CommandLineRunner 的一篇文章并在那里看到。这是个问题吗?\
  • @AndrewTobilko 提到的原因之一是 - 在不同的环境中分离命令行运行器。在生产中,您可能不想导入数据。
  • 另外,为什么要使用 Spring 而不是为这项工作而构建的工具:flywaydb.org
  • @SofoGial 不能通过 Spring 实现吗?

标签: java spring spring-boot spring-mvc


【解决方案1】:

个人资料在这里完全无关紧要。您可以通过执行以下操作来确保在数据导入之前创建架构:

@Component("schemaCreator")
public class SchemaCreator {

    @PostConstruct
    public void initSchema(){

    }
}

数据导入器可以依赖于通过 @DependsOn 注释初始化的架构。

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/DependsOn.html

当前 bean 所依赖的 bean。指定的任何 bean 都是 保证由容器在此 bean 之前创建。用过的 在 bean 没有显式依赖的情况下很少出现 另一个通过属性或构造函数参数,而是 取决于另一个 bean 初始化的副作用。

@DependsOn("schemaCreator")
@Component
public class DataImporter {

    @PostConstruct
    public void initData(){

    }
}

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 2015-02-23
    • 1970-01-01
    • 2017-05-26
    • 2016-03-04
    • 2016-10-04
    • 2023-03-28
    • 2014-12-25
    • 1970-01-01
    相关资源
    最近更新 更多