【问题标题】:Spring not overriding active profile from command line [duplicate]Spring没有从命令行覆盖活动配置文件[重复]
【发布时间】:2019-05-28 00:08:57
【问题描述】:

这是我的 application.yml 文件:

spring:
  freemarker:
    template-loader-path: classpath:/templates

  datasource:
    url: jdbc:postgresql://localhost:5432/myapp
    username: postgres
    password: password
    driver-class-name: org.postgresql.Driver

  jpa:
    show-sql: true
    properties:
      hibernate:
        enable_lazy_load_no_trans: false
        jdbc:
          lob:
            non_contextual_creation: true
        dialect: org.hibernate.dialect.PostgreSQLDialect
    hibernate:
      ddl-auto: create-drop


---

spring:
  profiles:
    active: development


---

spring:
  profiles: staging

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

logging:
  level:
    root: DEBUG

---

spring:
  profiles: production

  jpa:
    show-sql: false
    hibernate:
      ddl-auto: update

我使用以下方式运行应用程序:

java -jar application.jar -Dspring.profiles.active=staging

在日志中,我可以看到 spring boot 打印出来: 以下配置文件处于活动状态:开发

那么为什么即使我在命令行参数中明确设置了活动配置文件,也没有将其设置为staging

【问题讨论】:

    标签: java spring spring-boot spring-profiles


    【解决方案1】:

    顺序很重要。要设置系统属性,请使用

    java -jar -Dspring.profiles.active=staging application.jar
    

    你提到的那行传递了一个应用程序参数。

    【讨论】:

      【解决方案2】:

      启动 Java 应用程序。通过命令

      java [ options ] -jar file.jar [ arguments ]
      

      弹簧配置文件 spring-docs

      Spring 环境为此提供了一个 API,但您通常需要设置系统属性 (spring.profiles.active) 或操作系统环境变量 (SPRING_PROFILES_ACTIVE)。此外,您可以使用 -D 参数启动您的应用程序(请记住将其放在主类或 jar 存档之前),如下所示:

      $ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
      

      在 Spring Boot 中,您还可以在 application.properties 中设置活动配置文件,如下例所示:

      spring.profiles.active=production
      

      您可以使用 spring.profiles.active 环境属性来指定哪些配置文件处于活动状态,您也可以使用以下开关在命令行中指定它:spring-docs

      $ java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
      

      对于多个配置文件

      $ java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev,hsqldb
      

      【讨论】:

      • " --spring.profiles.active=dev,hsqldb " 这实际上是如何工作的?如果我在同一台服务器上运行真的很重要吗?最后会采用哪些属性?
      • 从文档docs.spring.io/spring-boot/docs/current/reference/html/…The spring.profiles.active property follows the same ordering rules as other properties: The highest PropertySource wins 看来hsqldb 是@Sam 的最高优先级
      【解决方案3】:

      你必须在你的 jar 文件之前指定选项并在它之后指定参数

      java [-options] -jar jarfile [args...]
      

      -Dspring.profiles.active=staging 是一个选项而不是参数。所以请改成下面的样子

      java -jar -Dspring.profiles.active=staging application.jar
      

      【讨论】:

        猜你喜欢
        • 2015-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 1970-01-01
        • 2016-08-31
        • 2020-01-20
        相关资源
        最近更新 更多