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

Spring not overriding active profile from command line

这是我的 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 引导打印出来: 以下配置文件处于活动状态:开发

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

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

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

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

您必须在 jar 文件之前指定选项并在其之后指定参数

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

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

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

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

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

Spring 配置文件 spring-docs

The Spring Environment has an API for this, but you would normally set a System property (spring.profiles.active) or an OS environment variable (SPRING_PROFILES_ACTIVE). Also, you can launch your application with a -D argument (remember to put it before the main class or jar archive), as follows:

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

In Spring Boot, you can also set the active profile in application.properties, as shown in the following example:

spring.profiles.active=production

You can use a spring.profiles.active Environment property to specify which profiles are active, You could also specify it on the command line by using the following switch: spring-docs

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

For multiple profiles

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