Spring 引导未加载特定配置文件

Spring boot not loading specific profile

我无法从命令行加载特定的 Spring 引导配置文件。

applciation.yml文件内容如下,放在我的应用程序的资源文件夹中。

server:
    port: 8787
spring:
  application:
    name: demo

spring:
  profiles: local_mysql
  datasource:
    url: jdbc:mysql://localhost:3306/demo?createDatabaseIfNotExist=true
    username: root
    password: root
    driverClassName: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
      dialect: org.hibernate.dialect.MySQLDialect
server:
    port: 8787

spring:
  profiles: development
  datasource:
    url: jdbc:mysql://localhost:3306/demo?createDatabaseIfNotExist=true
    username: admin
    password: admin
    driverClassName: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
      dialect: org.hibernate.dialect.MySQLDialect
server:
    port: 8788

执行后mvn clean package 运行 申请 java -jar -Dspring.profiles.active=local_mysql target\demo-1.0.0-SNAPSHOT.jar

应用程序忽略指定的配置文件,仅使用 H2 Db 在 8080 上启动 mySQL。

创建名为 application-local_mysql.yml 的单独文件,并在该文件中包含 local_mysql 相关设置。对所有配置文件执行相同的操作。在 application.yml 中具有所有配置文件通用的配置。

文件应位于 $CLASSPATH\config\ 位置。

然后运行你的申请。

java -jar -Dspring.profiles.active=local_mysql target\demo-1.0.0-SNAPSHOT.jar

参考:Externalized Configuration

在我看来,最好为不同的配置文件创建许多 yml 文件(如 @karthikeyan-vaithilingam post 中所述),但请注意 - 您可以在其中拥有多个配置文件的属性 application.yml - 这里尤里卡用法示例:

---
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
    metadataMap:
      # Each eureka instance need unique id. By default its hostname so we would have to use 1 server per service
      instanceId: PEER1_${spring.application.name}:${spring.application.instance_id:${random.value}}
---
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
    metadataMap:
  # Each eureka instance need unique id. By default its hostname so we would have to use 1 server per service
      instanceId: PEER2_${spring.application.name}:${spring.application.instance_id:${random.value}}