简体   繁体   中英

Externalizing values inside application.properties (ex. server.port, spring.datasource.url, and etc.)

server.port = ?
spring.datasource.url = ?
spring.datasource.username = ?
spring.datasource.password = ?

I want to externalize all the "?" values outside the application.properties, and have them in a text file or something.

I already have a configuration.txt file which holds other values, used in the services, but I just don't know how it works for the application.properties.

Solved, just have the property file in the same path where the jar file is, then spring boot will replace the values for you.

Spring.io Externalized Configuration

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

Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
@TestPropertySource annotations on your tests.
properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
Command line arguments.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
ServletConfig init parameters.
ServletContext init parameters.
JNDI attributes from java:comp/env.
Java System properties (System.getProperties()).
OS environment variables.
A RandomValuePropertySource that has properties only in random.*.
Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
Application properties outside of your packaged jar (application.properties and YAML variants).
Application properties packaged inside your jar (application.properties and YAML variants).

What this means is that what you want to do is supported without needing to do anything fancy inside your application.properties file.

Spring Boot will look at the application.properties file outside of your jar and consider any values in there and use them instead of any values in the application.properties file inside of your jar.

So, wherever your jar is, put the application.properties file you want for that environment. See the link for more details on just how much you can customize this (profiles, YAML, system properties, environment variables, etc.)

You might also consider moving to a Spring Cloud Config implementation, but that's a bit more work.

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