简体   繁体   中英

In Spring Boot, how do you build a JAR file for a different profile even if proper environment variables have not been set?

I'm new to Spring Boot, so bear with me. Currently, I'm working on a small app just for the purposes of learning Spring Boot. My goal is to deploy it using AWS (elastic beanstalk).

So far, I've created three application properties files:

  • application.properties: Properties which apply to all profiles.
  • application-dev.properties: Properties only for development. This includes localhost connection to DB, path to self signed key store, etc.
  • application-prod.properties: Properties used only for prod. This includes the prod DB details, etc.

Everything works fine when running the app locally using the dev profile since everything has been hard coded in the application-dev.properties.

However, the application-prod.properties file contains references which will be resolved through OS environment variables, such as:

spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}  

I currently do not have the variables DB_USERNAME and DB_PASSWORD set up in my local OS, and I do not wish to do so. But when I run the following command, it obviously fails:

mvn package spring-boot:repackage -Dspring.profiles.active=prod  

It fails because it's unable to find the above environment variables.

Is there any way to delay this check until I actually execute the JAR? My plan is to build the JAR locally and then copy it over to my prod server, and run it there. The prod server will definitely have these environment variables.

The workaround I found is this:

mvn package spring-boot:repackage -Dspring.profiles.active=dev
java -jar -Dspring.profiles.active=prod [jar-file-name].jar  

However, this feels like a hack. And it may cause issues in the future that I can't think of right now.

You can use any value you want in those properties for prod profile. If the env varieble exists, Spring will take the value from there instead of the properties.

As explained here :

Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:

[...]

  1. OS environment variables.

[...]

  1. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).

So your application-prod.properties can look like this:

spring.datasource.username=willBeOverridenByEnvValue
spring.datasource.password=willBeOverridenByEnvValue

You have to make sure though that you set both SPRING_DATASOURCE_USERNAME and SPRING_DATASOURCE_PASSWORD env values in your prod server

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