java - 使用 CommandLineRunner spring boot 创建模式

标签 java spring spring-boot spring-mvc

在我的 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

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

当 import-data 运行时,我收到一个错误

relation schema_name.table_name does not exist

但是,一旦创建了架构并再次运行应用程序 - 它就可以工作了。因此,当我必须部署我的应用程序时,每次我必须创建一个架构来运行一些集成测试时,它都会失败。

我运行的顺序是否错误?

最佳答案

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

@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

Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization.

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

    @PostConstruct
    public void initData(){

    }
}

关于java - 使用 CommandLineRunner spring boot 创建模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590870/

相关文章:

java - REST API 架构

java - 使用 Guice 在所有对象中注入(inject)实例

java - Java 是否有内置的静态反序列化能力或标准模式?

java - 由 : org. postgresql.util.PSQLException 引起:致命:用户 "admin"的密码验证失败

tomcat - Spring Boot是如何控制Tomcat缓存的?

Java 我怎样才能添加这个? Python 已经具备的地方

spring - 具有一对多关系的 Spring Boot 的无限循环

spring - 如何配置spring HandlerExceptionResolver来处理jsp中抛出的NullPointerException?

java - 找不到匹配项时 JPA 查询的返回值

java - 可以将自定义数据返回给 Kafka Producer