简体   繁体   中英

Spring boot not loading specific profile

I am unable to load specific Spring boot profile from command line.

applciation.yml file content is as follows and it is placed inside resource folder of my application.

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

After executing mvn clean package and running application with java -jar -Dspring.profiles.active=local_mysql target\\demo-1.0.0-SNAPSHOT.jar

Application ignores specified profile and just starts on 8080 with H2 Db instead mySQL.

Create separate file named application-local_mysql.yml and have the local_mysql related settings in that file. Do the same for all the profiles. In application.yml have the configurations common to all profiles.

The files should be in $CLASSPATH\\config\\ location.

Then run your application.

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

Ref: Externalized Configuration

In my opinion its better to create many yml files for different profiles (as mentioned in @karthikeyan-vaithilingam post), but just for note - you can have properties for more than one profile inside application.yml - here eureka usage example:

---
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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM