外部化application.properties内部的值(例如server.port,spring.datasource.url等)

时间:2019-09-20 14:20:11

标签: spring-boot application.properties externalizing

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

我想将所有的“?”值在application.properties之外,并将其保存在文本文件或其他内容中。

我已经有一个configuration.txt文件,其中包含服务中使用的其他值,但我只是不知道它如何用于application.properties。

已解决,只需将属性文件放在jar文件所在的路径中,然后Spring Boot将为您替换这些值。

1 个答案:

答案 0 :(得分:0)

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).

这意味着您想要做的事情得到了支持,而无需在application.properties文件中做任何花哨的事情。

Spring Boot将查看jar的外部外部的application.properties文件,并考虑其中的任何值,并代替使用它们在application.properties文件中的任何值在罐子里

因此,无论您的jar放在哪里,都将您要用于该环境的application.properties文件放入。请参阅链接以获取有关您可以自定义多少(配置文件,YAML,系统属性,环境变量等)的更多详细信息。

您可能还考虑迁移到Spring Cloud Config实现,但这还需要做很多工作。