Spring/Spring Boot的外部化配置
Posted dongyuanshi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring/Spring Boot的外部化配置相关的知识,希望对你有一定的参考价值。
不论是一个简单的Java程序或者是基于Spring或者Spring Boot框架实现的程序,都存在外部化配置信息的需求,例如一个抽奖程序需要制定随机器的种子值,或者与数据库建立连接的url/username/password,这些配置信息你都不希望直接固定写入程序中,因此需要一种方式能够外部化制定这些配置信息,在代码的对这些数据的使用点读取对应的配置来实现动态化程序的行为。
1. 环境变量(System.getEnv)
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:Windows
etc, and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
2. Java系统属性(System.getProperties)
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime using System.setProperty(String key, String value)
or via the various System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
. As it happens, Java chose to expose OS variables as properties (just as Java exposes current directory and "other stuff" as properties)
Different from Environment Variables: https://www.baeldung.com/java-system-get-property-vs-system-getenv
3. spring的外部化配置策略
spring.config.location, 只对spring boot有效,查找配置文件的详细地址。
Property and Enviroment
application.properties/.yml
Common sub project configuration
above spring 3.1 and below spring 3.1 , propertysourceplaceholder propertyplaceholder <context: place-holder> @PropertySource
以上是关于Spring/Spring Boot的外部化配置的主要内容,如果未能解决你的问题,请参考以下文章