Spring无法从命令行覆盖活动配置文件

9

这是我的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输出了以下内容:激活的配置文件为: development 那么,为什么即使我在命令行参数中明确设置了staging,激活的配置文件仍然没有被设置为它呢?
3个回答

19

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

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

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


5

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

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

Spring Profiles 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” 这个是怎么工作的?如果我在同一台服务器上运行,它真的有影响吗?最终会采用哪些属性? - Prasanna Kumar H A
从文档 https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-adding-active-profiles 中可以看到,spring.profiles.active 属性遵循与其他属性相同的排序规则:最高的 PropertySource 获胜。对我来说似乎 hsqldb 优先级最高。@Sam - Ryuzaki L

3

在运行JAR文件之前,您需要指定选项,并在其后添加参数。

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

-Dspring.profiles.active=staging是一个选项而不是参数。请将其更改为以下内容:
java -jar -Dspring.profiles.active=staging application.jar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接