Back to Javatutorial

SpringBoot的配置文件管理

docs/Spring全家桶/SpringBoot/SpringBoot的配置文件管理.md

1.0.044.6 KB
Original Source

1.SpringBootùı

ΪʵֿٴͿĿSpringbootܴspringbootĿԽĿֱӴjarУԼװTomcatһַݵIJʽ

Ŀķʽһjar𣬼ļ͵jarͻ

һĿйУҪĶļĻҪ´

ĿҪͬһ̨ʱԵjarͬĵĿjar100Mܾռ99M˷Դ˷ԼĿЧʡ

ĿļȡjarͳһĿЧֽԼ˷ĴģͬʱĿάҲǷdzģĶļ·Ϳˣ¹

Ǿʵַ

1.1 ļͳһ

	- springbootļ
	- Springbootȡļapplication.propertiesȼΪ
	- JarͬĿ¼configĿ¼
	- JarͬĿ¼
	- classPath(resourcesĿ¼)configĿ¼
	- classpathĿ¼

springbootĬȥԼĺļȼһȼķʽĿʱͨķʽָĿغļ java Cjar -Dspring.config.location=xxx/xxx/xxxx.properties xxxx.jar

Spring Bootȼߵλҵãôȼ͵

1.2 Դļ

SpringbootļѾܹȡjarйˣǻһЩҵϵļԴļԴļFTPϢȣquartzʱ־ļȥȡȷڴõ

֪SpringbootĿͨעⷽʽȡļҲͨעⷽʽĿܹõjarⲿļģͼ

@PropertySourcevalueֵһclasspathconfigĿ¼µԴļڶǸspring.profiles.path̬ȡĿ¼spring.profiles.pathںļԶһֵļͳһļ·ignoreResourceNotFound=true趨ǰһ·ûҵļݵڶ·ȥҡ

ǻֱӸ·FileSystemResourceȥһļʵͼ

ԭƣںļԶͳһĿ¼·ļ

logback־ļطʽ£

һʵַ˼·

	- springbootļﶨһspring.profiles.pathֵָļͳһõĿ¼ļҲǷ

	- ļļĵطҲӦûȡspring.profiles.path̬ظ·µļ

	- Pom.xmlļ޸Ĵģ飬ļųǴjarDzļģοĵڵ3

	- jarʱָͨصĺļΪspring.profiles.pathµĺļ

ͳһ

ͨjarԴjarҲԷĿjarͬĿ¼µlibĿ¼ǿԸ޸pom.xmlʵ֣οĵڵ3


<build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
				</includes>
				<filtering>true</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<!ʱųļ-->
                                <excludes>
					<exclude>**/*.properties</exclude>
					<exclude>**/*.xml</exclude>
					<exclude>**/*.yml</exclude>
				</excludes>
				<filtering>false</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				maven-compiler-plugin
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<fork>true</fork>
					<skip>true</skip>
					<executable>
						C:/Program Files/Java/jdk1.8.0_161/bin/javac.exe
					</executable>
				</configuration>
			</plugin>
			<plugin>
				maven-jar-plugin
				<configuration>
					
						<manifest>
							true
							<classpathPrefix>lib/</classpathPrefix>
							<useUniqueVersions>false</useUniqueVersions>
							<mainClass>com.xrq.demo.Application</mainClass>
						</manifest>
						<manifestEntries>
							<Class-Path>./</Class-Path>
						</manifestEntries>
					
					<excludes>
						<exclude>*.properties</exclude>
						<exclude>*.yml</exclude>
						<exclude>*.xml</exclude>
						<exclude>config/**</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				maven-dependency-plugin
				<executions>
					<execution>
						<id>copy</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>
								${project.build.directory}/lib
							</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

ĺpom.xmlbuildģ󣬾Ϳͨmvn package mvn installǵjar

  1. Ŀshellűд ԶshellűʵĿֹͣ״̬
#!/bin/bash 
#滻ΪԼִг, 
APP_NAME=demo1-0.0.1-SNAPSHOT.jar 
JVM="-server -Xms512m -Xmx512m -XX:PermSize=64M -XX:MaxNewSize=128m -XX:MaxPermSize=128m -Djava.awt.headless=true -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled"
APPFILE_PATH="-Dspring.config.location=/usr/local/demo/config/application-demo1.properties"
#ʹ˵,ʾ 
usage() { 
echo "Usage: sh ִнű.sh [start|stop|restart|status]" 
exit 1 
} 
#Ƿ 
is_exist(){ 
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' ` 
#ڷ1,ڷ0 
if [ -z "${pid}" ]; then 
return 1 
else 
return 0 
fi 
} 
# 
start(){ 
is_exist 
if [ $? -eq "0" ]; then 
echo "${APP_NAME} is already running. pid=${pid} ." 
else 
nohup java $JVM -jar $APPFILE_PATH $APP_NAME > /dev/null 2>&1 
fi
} 
#ֹͣ 
stop(){ 
is_exist 
if [ $? -eq "0" ]; then 
kill -9 $pid 
else 
echo "${APP_NAME} is not running" 
fi 
} 
#״̬ 
status(){ 
is_exist 
if [ $? -eq "0" ]; then 
echo "${APP_NAME} is running. Pid is ${pid}" 
else 
echo "${APP_NAME} is NOT running." 
fi 
} 
# 
restart(){ 
stop 
start 
} 
#,ѡִжӦ,ִʹ˵ 
case "$1" in 
"start") 
start 
;; 
"stop") 
stop 
;; 
"status") 
status 
;; 
"restart") 
restart 
;; 
*) 
usage 
;; 
esac


linux½ļУǴõĿjarȥjarͬĿ¼½configlibļУֱļ͵ȥṹͼ*.shΪԼдĿshellű

configڵspringbootļapplication-demo1.propertiesļ

spring.profiles.pathijɵǰļڵĿ¼Ϊ/usr/local/demo/config

*.shű޸APPFILE_PATHֵ

APPFILE_PATH="-Dspring.config.location=/usr/local/demo/config/application-demo1.properties"

Ŀ

jarĿ¼ִ

sh demo1.sh start Ŀ

sh demo1.sh stop ֹͣĿ

sh demo1.sh restartĿ

sh demo1.sh statusĿ״̬

2. ⲿ

Spring Boot㽫ⲿͿڲͬĻʹͬӦó롣 ʹøⲿԴJava properties ļYAMLļв

ֵͨʹ @Value עֱעBeanҲͨSpring Environment ʣͨ @ConfigurationProperties 󶨵

Spring Boot ʹһdzر PropertySource ˳ּдֵ property source ԸǰԴжֵ ˳ǡ

  1. Ĭԣͨ SpringApplication.setDefaultProperties ָ

  2. @Configuration ϵ @PropertySource ע⡣ע⣬Դֱapplication contextˢʱŻᱻӵСijЩ˵Ѿ̫ˣ logging.* spring.main.* ˢ¿ʼǰѾȡˡ

  3. ݣ application.properties ļ

  4. RandomValuePropertySourceֻ random.* ԡ

  5. ϵͳ

  6. Java System properties (System.getProperties()).

  7. java:comp/env е JNDI ԡ

  8. ServletContext init parameters.

  9. ServletConfig init parameters.

  10. SPRING_APPLICATION_JSON ԣǶ뻷ϵͳеJSON

  11. в

  12. ڲе properties ԡ @SpringBootTest ͲעпãڲӦóһضƬ

  13. еhttps://docs.spring.io/spring-framework/docs/6.0.5/javadoc-api/org/springframework/test/context/TestPropertySource.html[`@TestPropertySource`] ע.

  14. devtoolsڻ״̬ʱ$HOME/.config/spring-boot Ŀ¼µDevtoolsȫ

ļ˳ǡ

  1. jarдApplication propertiesapplication.properties YAML

  2. jarд ض Profile application propertiesapplication-{profile}.properties YAML

  3. jar֮Application propertiesԣapplication.propertiesYAML

  4. jar֮ض Profile application properties application-{profile}.properties YAML

Ӧóмʹһָʽ ͬһط .properties .yml ʽļ.properties ȡ

Ϊṩһӣ㿪һ @Componentʹһ name ԣʾ

Java

Kotlin

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

Ӧóclasspath磬jarУһ application.properties ļΪ name ṩһĬֵһµĻʱjar֮ṩһ application.properties ļ name һԵIJԣһضв磬java -jar app.jar --name="Spring"

env configprops ˵ȷһΪʲôһضֵʱdzáʹ˵ֵ "" ֡

2.1.

Ĭ£SpringApplication Ὣκѡ -- ͷIJ --server.port=9000 תΪ property ӵSpring Environment С ǰڻļԴ

㲻ϣԱӵ Environment Уͨ SpringApplication.setAddCommandLineProperties(false) ǡ

2.2. JSON Application Properties

ϵͳƣζЩƲʹá Ϊ˰⣬Spring Boot㽫һԿΪһһJSONṹ

Ӧóʱκ spring.application.json SPRING_APPLICATION_JSON Խӵ Environment С

SPRING_APPLICATION_JSON Կ UN*X shell Ϊṩ

$ SPRING_APPLICATION_JSON='{"my":{"name":"test"}}' java -jar myapp.jar

ǰУSpring Environment յõ my.name=test

ͬJSONҲΪһϵͳṩ

$ java -Dspring.application.json='{"my":{"name":"test"}}' -jar myapp.jar

ͨʹһвṩJSON

$ java -jar myapp.jar --spring.application.json='{"my":{"name":"test"}}'

ҪһӦ÷УҲʹһΪ java:comp/env/spring.application.json JNDI

JSONе null ֵӵɵԴУ PropertySourcesPropertyResolver null Ϊȱʧֵ ζJSON null ֵԵͽԴԡ

2.3. ⲿ Application Properties

ӦóʱSpring BootԶλҵ application.properties application.yaml ļ

  1. classpath

    1. classpath ·

    2. classpath µ /config

  2. ǰĿ¼

    1. ǰĿ¼

    2. ǰĿ¼µ config/ Ŀ¼

    3. config/ Ŀ¼ֱĿ¼

бȼ򣨽ϵĿֵǽĿֵ صļΪ PropertySources ӵSpring Environment С

㲻ϲ application Ϊļƣָͨ spring.config.name лһļơ 磬ΪѰ myproject.properties myproject.yaml ļ԰·ʽӦó

$ java -jar myproject.jar --spring.config.name=myproject

Ҳͨʹ spring.config.location һȷλá ԽһŷָбаһҪλá

ʾָͬļ

$ java -jar myproject.jar --spring.config.location=\
    optional:classpath:/default.properties,\
    optional:classpath:/override.properties
ļǿѡҿDzڵģôʹ optional: ǰ׺
spring.config.name, spring.config.location, spring.config.extra-location ȷЩļ뱻ء DZ뱻ΪԣͨDzϵͳϵͳԣв

spring.config.location Ŀ¼ļӦ / β ʱǽ spring.config.name ɵƣȻ󱻼ء spring.config.location ָļֱӵ롣

Ŀ¼ļλֵҲչԼضļspring.config.location classpath:myconfig.propertiesҲᷢʵ classpath:myconfig-<profile>.properties ļء

ڴ£ӵÿ spring.config.location һļĿ¼ λǰDZ˳ģλÿԸǰλõֵ

һӵλãʹضļҪṩһʾԱSpring Boot֪Ӧη顣һλһλõļϣЩλöΪͬһ磬classpathλ÷飬ȻⲿλáһλڵĿӦ ; ָϸڼ ָ profile ֵӡ

ͨʹ spring.config.location õλȡĬλá 磬 spring.config.location Ϊ optional:classpath:/custom-config/,optional:file:./custom-config/ ǵλü¡

  1. optional:classpath:custom-config/

  2. optional:file:./custom-config/

ϲӶλã滻ǣʹ spring.config.extra-location ӸλüصԿԸĬλõԡ 磬 spring.config.extra-location Ϊ optional:classpath:/custom-config/,optional:file:./custom-config/ ǵλü¡

  1. optional:classpath:/;optional:classpath:/config/

  2. optional:file:./;optional:file:./config/;optional:file:./config/*/

  3. optional:classpath:custom-config/

  4. optional:file:./custom-config/

һļָĬֵȻһļѡԵظЩֵ һĬλõ application.properties spring.config.name ѡbasenameΪӦóṩĬֵ ȻЩĬֵʱλһԶλõIJͬļǡ

ʹûϵͳԣϵͳʹþָļʹ»ߴ棨磬 SPRING_CONFIG_NAME spring.config.name μӻ ˽顣
ӦóservletӦ÷УôJNDIԣ java:comp/env УservletijʼԴ滷ϵͳԣ֮һ

2.3.1. ѡλ(Optional Locations)

Ĭ£ָλòʱSpring Boot׳һ ConfigDataLocationNotFoundException Ӧó޷

ָһλã㲻Ǵڣʹ optional: ǰ׺ spring.config.locationspring.config.extra-location ʹǰ׺Ҳ spring.config.import ʹá

spring.config.import ֵΪ optional:file:./myconfig.properties Ӧóʹ myconfig.properties ļʧ

е ConfigDataLocationNotFoundExceptions ʼռӦóʹ spring.config.on-not-found ԡ ʹ SpringApplication.setDefaultProperties(..) ʹϵͳ/ֵΪ ignore

2.3.2. ַͨ

һļλһ·а * ַͱΪһͨλá ͨڼʱչˣֱӵĿ¼Ҳ顣 ͨλKubernetesжԵԴĻرá

磬һЩRedisúһЩMySQLã÷ֿͬʱҪֶһ application.properties ļС

ܻᵼ application.properties ļڲͬλã /config/redis/application.properties /config/mysql/application.properties £һͨλ config/*/ ļ

Ĭ£Spring Boot config/*/ Ĭλá ζjar֮ /config Ŀ¼Ŀ¼ᱻ

spring.config.location spring.config.extra-location ʹͨλá

ͨλñֻһ * */ βĿ¼λã */<filename> ļλá ͨλýļľ·ĸ˳
ͨλֻⲿĿ¼á 㲻 classpath: λʹͨ

2.3.3. ضļProfile Specific Files

application ļSpring Bootʹ application-{profile} profileضļ 磬Ӧó򼤻Ϊ prod ļspring.profiles.active=prodʹYAMLļô application.yml application-prod.yml ǡ

ضļ(profilesapplication.properties λͬضļڷضļ ָ˼ļʤIJԡ 磬ļ prod,live spring.profiles.active ָģapplication-prod.properties еֵԱ application-live.properties еֵǡ

ʤIJlocation group spring.config.location classpath:/cfg/,classpath:/ext/ classpath:/cfg/;classpath:/ext/ ͬĸǹ磬 prod,live ˵ǿļ /cfg application-live.properties/ext application-live.properties application-prod.properties һ spring.config.location Ϊ classpath:/cfg/,classpath:/ext/ ʱǻ /ext ļ֮ǰ /cfg ļ1. /cfg/application-live.properties 2. /ext/application-prod.properties 3. /ext/application-live.properties classpath:/cfg/;classpath:/ext/ ʱ ; ָͬһ /cfg /ext 1. /ext/application-prod.properties 2. /cfg/application-live.properties 3. /ext/application-live.properties

Environment һĬϵļĬΪ [default] ûûļͻʹЩļ 仰˵ûȷļôͻῼ application-default ԡ

ļֻһΡ Ѿֱһļضļôᱻڶε롣

2.3.4.

application properties пʹ spring.config.import Դطݡ ڱʱΪļĶļ

磬 classpath application.properties ļݡ

Properties

Yaml

spring.application.name=myapp
spring.config.import=optional:file:./dev.properties

⽫뵱ǰĿ¼µ dev.properties ļļ dev.properties еֵڴļ Уdev.properties Խ spring.application.name ¶Ϊһֵͬ

һֻᱻһΣٴΡ һproperties/yamlļڵĵļб˳򲢲Ҫ 磬ӲͬĽ

Properties

Yaml

spring.config.import=my.properties
my.property=value

Properties

Yaml

my.property=value
spring.config.import=my.properties

Уmy.properties ļֵڴ䵼ļ

һһ spring.config.import ¿ָλá λýDZ˳򱻴ĵ뽫ȴ

ʵʱضļıҲǵ롣 ӽ my.properties Լκ my-<profile>.properties
Spring Boot ṩ˿ɲεAPIֲָ֧ͬλõַ Ĭ£ԵJava PropertiesYAML jarṩ֧֣ҪDZļ 磬ⲿ洢ConsulApache ZooKeeperNetflix ArchaiusNacos֧ԼλãʵԼüأ org.springframework.boot.context.config е ConfigDataLocationResolver ConfigDataLoader

2.3.5. չļ

Щƽ̨Ϊװļvolume mounted filesļչ ҪЩչļҪSpring BootһʾԱ֪μǡ ͨչʾڷһ㡣

磬һ /etc/config/myconfig ļϣyamlʽ롣 ķ application.properties е

Properties

Yaml

spring.config.import=file:/etc/config/myconfig[.yaml]

2.3.6. ʹConfiguration Trees

ƽ̨KubernetesӦóʱ㾭Ҫȡƽ̨ṩֵ ڴĿIJټȱ㣬رֵ secret ġ

Ϊƽ̨㽫ӳ䵽صݾ 磬Kubernetes Ծ ConfigMaps Secrets

ʹֳ volume ģʽ

  1. һļһԣͨдYAML

  2. ļдһĿ¼УļΪ keyݳΪ value

ڵһʹ spring.config.import ֱӵYAMLļ ڵڶҪʹ configtree: ǰ׺ԱSpring Boot֪ҪļΪԹ

ٸӣһ£KubernetesѾvolume

etc/ config/ myapp/ username password

username ļݽһֵ password ݽһ secret

ҪЩԣ application.properties application.yaml ļݡ

Properties

Yaml

spring.config.import=optional:configtree:/etc/config/

ȻԴ Environment Գ淽ʽʻע myapp.username myapp.password ԡ

µļйơ УΪ˷Ϊ username passwordԽ spring.config.import Ϊ optional:configtree:/etc/config/myapp
еŵļҲᱻȷӳ䡣 磬У/etc/config Ϊ myapp.username ļ Environment е myapp.username
ֵԱ󶨵ַ String byte[] ͣȡԤڵݡ

жҪͬһļе룬ʹͨݷʽ κ /*/ β configtree: λýֱӵļΪ

磬volume

etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password

ʹ configtree:/etc/config/*/ Ϊλá

Properties

Yaml

spring.config.import=optional:configtree:/etc/config/*/

db.username``db.password``mq.username mq.password ԡ

ʹͨصĿ¼ǰĸ˳еġ Ҫһͬ˳ôӦðÿλΪһĵг

ҲDocker secret Docker swarmsecretķȨʱsecretᱻװصС 磬һΪ db.password secret /run/secrets/ λã· db.password Springá

Properties

Yaml

spring.config.import=optional:configtree:/run/secrets/

2.3.7. ռλ

application.properties application.yml еֵʹʱͨе Environment ˣԲοǰֵ磬ϵͳԻ򻷾 ׼ ${name} ռλ﷨һֵκεط ռλҲָһĬֵʹ : ָĬֵƣ ${name:default}

ʾ˴ĬֵͲĬֵռλʹ

Properties

Yaml

app.name=MyApp
app.description=${app.name} is a Spring Boot application written by ${username:Unknown}

username ûطãapp.description ֵ MyApp is a Spring Boot application written by Unknown

ӦʼʹռλеƵĹ淶ʽʹСдĸkebab-caseǡ ⽫Spring Bootʹɰ @ConfigurationProperties ʱͬ߼磬${demo.item-price} application.properties ļлȡ demo.item-price demo.itemPrice ʽԣԼϵͳлȡ DEMO_ITEMPRICE ${demo.itemPrice} Ļ demo.item-price DEMO_ITEMPRICE Ͳᱻǡ
ҲʹּSpring BootԵ short 塣 μ_howto.html

2.3.8. ʹöĵļWorking with Multi-Document Files

Spring Boot㽫һļֳɶ߼ļÿļǶӵġ ļǰ˳ģϵ¡ ļԸǰļжԡ

application.yml ļʹñ׼YAMLĵ﷨ ַ---һļĽһļĿʼ

磬ļ߼ĵ

spring:
  application:
    name: "MyApp"
---
spring:
  application:
    name: "MyCloudApp"
  config:
    activate:
      on-cloud-platform: "kubernetes"

application.properties ļһ #--- !--- עͱļķָ

spring.application.name=MyApp
#---
spring.application.name=MyCloudApp
spring.config.activate.on-cloud-platform=kubernetes
properties ļķָκǰհףұַ ָǰвͬעǰ׺
ĵļͨ뼤һʹã spring.config.activated.on-profile һ
ĵļͨʹ @PropertySource @TestPropertySource עء

2.3.9. ԣActivation Properties

ʱֻijЩʱһضǺõġ 磬һЩֻضļʱء

ʹ spring.config.activation.* ؼһļ

¡

<caption>Table 2\. activation properties</caption><colgroup><col><col></colgroup> | | ˵ | | --- | --- | | `on-profile` | һ֮ƥļʽʹļڻ״ָ̬ļʱЧ | | `on-cloud-platform` | ⵽ `CloudPlatform`ʹļڻ״̬ƽ̨״̬Ч |

磬ָڶļֻKubernetesʱЧֻ prod staging ļڻ״̬ʱЧ

Properties

Yaml

myprop=always-set
#---
spring.config.activate.on-cloud-platform=kubernetes
spring.config.activate.on-profile=prod | staging
myotherprop=sometimes-set

2.4. ԣEncrypting Properties

Spring BootûΪֵṩκ֧֣ṩHookm޸Spring Environment аֵ EnvironmentPostProcessor ӿӦóǰ Environment μhowto.html˽顣

Ҫһְȫķʽ洢ƾ֤룬 Spring Cloud Vault Ŀṩ˶ HashiCorp Vaultд洢ⲿõ֧֡

2.5. ʹ YAML

YAML JSONijֲָݵķʽ ֻҪclasspath SnakeYAMLSpringApplication ͻԶ֧YAMLΪpropertiesƷ

ʹ StarterSnakeYAML spring-boot-starter Զṩ

2.5.1. YAMLӳ䵽Properties

YAML ĵҪֲʽתΪ Spring Environment һʹõıƽṹ 磬YAMLĵ

environments:
  dev:
    url: "https://dev.example.com"
    name: "Developer Setup"
  prod:
    url: "https://another.example.com"
    name: "My Cool App"

Ϊ˴ Environment зЩԣǽƽʾ

environments.dev.url=https://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=https://another.example.com
environments.prod.name=My Cool App

ͬأYAMLебҲҪбƽ DZʾΪ [index] key 磬YAML

my:
 servers:
 - "dev.example.com"
 - "another.example.com"

ǰӽתΪԡ

my.servers[0]=dev.example.com
my.servers[1]=another.example.com
ʹ [index] ŵԿʹSpring Boot Binder 󶨵Java List Set ϸڼ Ͱȫ ֡
YAMLļͨʹ @PropertySource @TestPropertySource עء ԣҪַʽֵ£Ҫʹһ properties ļ

2.5.2. ֱӼYAML

Spring Frameworkṩ࣬YAMLĵ YamlPropertiesFactoryBean YAMLΪ Properties أYamlMapFactoryBean YAMLΪ Map ء

YAMLΪSpring PropertySource Ҳʹ YamlPropertySourceLoader

2.6. ֵ

The RandomValuePropertySource is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example:

RandomValuePropertySource עֵã磬ע԰ ԲIntegerLongUUIDStringʾ

Properties

Yaml

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number-less-than-ten=${random.int(10)}
my.number-in-range=${random.int[1024,65536]}

random.int*OPEN value (,max) CLOSE OPEN,CLOSE κַ value,maxmaxô value Сֵ max ֵռ

2.7. ϵͳ

Spring Boot֧Ϊһǰ׺ ϵͳвͬҪSpring BootӦóͺá ϵͳԵǰ׺ֱ SpringApplication á

磬㽫ǰ׺Ϊ input remote.timeout ϵͳҲΪ input.remote.timeout

2.8. Ͱȫ

ʹ @Value("${property}") עעʱ鷳رǵҪԻǷֲġ Spring BootṩһִԵǿ͵Bean֤Ӧóá

μ@Value Ͱȫ֮

2.8.1. JavaBean ԰

ʾ԰һ˱׼JavaBeanԵbean

Java

Kotlin

@ConfigurationProperties("my.service")
public class MyProperties {

    private boolean enabled;

    private InetAddress remoteAddress;

    private final Security security = new Security();

    // getters / setters...

    public static class Security {

        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

        // getters / setters...

    }

}

ǰPOJOԡ

  • my.service.enabledĬֵΪfalse

  • my.service.remote-addressͿStringǿṩ

  • my.service.security.usernameһǶ׵ security ɸԵƾ رǣȫûʹͣ SecurityProperties

  • my.service.security.password.

  • my.service.security.roleһ String ļϣĬΪ USER

ӳ䵽Spring Bootпõ @ConfigurationProperties ԣͨpropertiesļYAMLļƽãЩǹAPI౾ getters/setters ζſֱʹãһ仰SpringҲͨgetter/setterЩpublicֵģã
һĬϵ޲ι캯gettersetterͨDZģΪͨ׼Java Beans property descriptorJavaʡʵֵģSpring MVCһ £ʡsetter* Map, ֻҪDZʼҪһgetterһҪһsetterΪǿԱͻ䡣 * Collectionarray ͨͨYAMLʹõŷֵָԣʡ ںһ£һsetterDZġ ǽΪһsetter ʼһϣȷDzɱģǰӣ * Ƕ׵POJOԱʼǰе Security ֶΣͲҪsetter ðͨʹĬϹ캯ʱʵҪһsetter ЩʹProject LombokԶgettersetter ȷLombokΪκضĹ캯ΪԶʵֻDZ׼Java Beanԣֶ֧Ծ̬Եİ󶨡

2.8.2. 캯

һڵӿòɱķʽдʾ

Java

Kotlin

@ConfigurationProperties("my.service")
public class MyProperties {

    // fields...

    public MyProperties(boolean enabled, InetAddress remoteAddress, Security security) {
        this.enabled = enabled;
        this.remoteAddress = remoteAddress;
        this.security = security;
    }

    // getters...

    public static class Security {

        // fields...

        public Security(String username, String password, @DefaultValue("USER") List<String> roles) {
            this.username = username;
            this.password = password;
            this.roles = roles;
        }

        // getters...

    }

}

УΨһġ캯ĴζӦʹøù캯а󶨡 ζŰҵһϣ󶨵IJĹ캯 ж캯ʹ @ConstructorBinding עָʹĸ캯й캯󶨡 ҪΪһֻһ캯ѡ񲻰󶨹캯ù캯 @Autowired ע⡣ 캯󶨿 Record һʹá ļ¼ж캯ûбҪʹ @ConstructorBinding

캯Ƕ׳Աе SecurityҲͨ乹캯󶨡

Ĭֵڹ캯Recordʹ @DefaultValue ָ ת񽫱Ӧڽע String ֵǿתΪȱʧԵĿ͡

οǰӣû԰󶨵 Security MyProperties ʵһ security ͵ null ֵ Ϊʹһ null Security ʵʹû֮󶨣ʹKotlinʱ⽫Ҫ Security username password Ϊ nullableΪûĬֵʹһյ @DefaultValue ע⡣

Java

Kotlin

public MyProperties(boolean enabled, InetAddress remoteAddress, @DefaultValue Security security) {
    this.enabled = enabled;
    this.remoteAddress = remoteAddress;
    this.security = security;
}

Ҫʹù캯󶨣ʹ @EnableConfigurationProperties ɨá 㲻ܶͨSpringƴBeanʹù캯󶨣 @Component Beanͨʹ @Bean Beanͨʹ @Import صBean
Ҫԭʹù캯󶨣 -parameters ࡣʹ Spring Boot Gradle ʹ Maven spring-boot-starter-parent⽫Զá
java.util.Optional @ConfigurationProperties һʹãΪҪΪһʹá ˣʺע롣 Ϊ͵Աһ£ȷʵһ Optional ԣûֵnull һյ Optional 󶨡

2.8.3. @ConfigurationProperties

Spring Bootṩ˰ @ConfigurationProperties ͲעΪBeanĻʩ Ļԣɨ裬乤ʽɨơ

ʱ @ConfigurationProperties עܲʺɨ裬磬ڿԼԶûǡ Щ£ʹ @EnableConfigurationProperties עָҪб עκ @Configuration ϣʾ

Java

Kotlin

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(SomeProperties.class)
public class MyConfiguration {

}

Java

Kotlin

@ConfigurationProperties("some.properties")
public class SomeProperties {

}

Ҫʹɨ裬application @ConfigurationPropertiesScan ע⡣ ͨӵ @SpringBootApplication עmainУҲԱӵκ @Configuration ϡ Ĭ£ɨעڵİʼԶɨԲο¡

Java

Kotlin

@SpringBootApplication
@ConfigurationPropertiesScan({ "com.example.app", "com.example.another" })
public class MyApplication {

}

@ConfigurationProperties Beanʹɨͨ @EnableConfigurationProperties עʱBeanһƣ<prefix>-<fqn> <prefix> @ConfigurationProperties עָĻǰ׺ <fqn> Beanȫ޶ơ עûṩκǰ׺ֻʹBeanȫ޶ơ com.example.app У SomeProperties ӵ bean some.properties-com.example.app.SomeProperties

ǽ @ConfigurationProperties ֻ environmentرDzעBean ڱ߽ǰʹ setter עṩκ *Aware ӿڣ EnvironmentAware Ҫ Environment ȻʹùעBeanBean @Component ע⣬ʹûJavaBean԰󶨡

2.8.4. ʹ @ConfigurationProperties

÷ʽ SpringApplication ⲿYAMLϵرãʾ

my:
  service:
    remote-address: 192.168.1.1
    security:
      username: "admin"
      roles:
      - "USER"
      - "ADMIN"

Ҫʹ @ConfigurationProperties BeanBeanͬķʽעǣʾ

Java

Kotlin

@Service
public class MyService {

    private final MyProperties properties;

    public MyService(MyProperties properties) {
        this.properties = properties;
    }

    public void openConnection() {
        Server server = new Server(this.properties.getRemoteAddress());
        server.start();
        // ...
    }

    // ...

}

ʹ @ConfigurationProperties ԪļЩļԱIDEԵġԶȫܡ ¼

2.8.5.

ʹ @ConfigurationProperties עһ֮⣬㻹ڹ @Bean ʹ ԰󶨵֮ĵʱرá

Ҫ Environment һBeanBeanע @ConfigurationProperties ʾ

Java

Kotlin

@Configuration(proxyBeanMethods = false)
public class ThirdPartyConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "another")
    public AnotherComponent anotherComponent() {
        return new AnotherComponent();
    }

}

κ another ǰ׺JavaBeanԶᱻӳ䵽 AnotherComponent Beanϣ䷽ʽǰ SomeProperties ӡ

2.8.6. ɵİ

Spring Bootڽ Environment ԰󶨵 @ConfigurationProperties beanʱʹһЩɵĹ Environment ƺbean֮䲻Ҫȫƥ䡣 ãӰۺŷָƣ磬 context-path 󶨵 contextPath ʹдƣ磬PORT 󶨵 port

ʾһӣ @ConfigurationProperties

Java

Kotlin

@ConfigurationProperties(prefix = "my.main-project.person")
public class MyPersonProperties {

    private String firstName;

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

ϵĴ˵µƶʹá

<caption>Table 3\. relaxed binding</caption><colgroup><col><col></colgroup> | Property | Note | | --- | --- | | `my.main-project.person.first-name` | Kebab 񣨶̺߸ `.properties` `.yml` ļʹá | | `my.main-project.person.firstName` | ׼շ﷨ | | `my.main-project.person.first_name` | »ߣһ `.properties` `.yml` ļʽ | | `MY_MAINPROJECT_PERSON_FIRSTNAME` | дʽʹϵͳʱʹôдʽ |
ע prefix ֵ __ kebabСд - ָ my.main-project.person
<caption>Table 4\. ÿԴĿɰ󶨹</caption><colgroup><col><col><col></colgroup> | Դ | 򵥵 | б | | --- | --- | --- | | Properties ļ | շ, kebab , » | ʹ `[ ]` 򶺺ŷֵָı׼б﷨ | | YAML ļ | շ, kebab , » | ׼YAMLб﷨򶺺ŷֵָ | | | д»Ϊָ( [ӻ](https://springdoc.cn/spring-boot/features.html#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables)). | Numeric values surrounded by underscores (see [ӻ](https://springdoc.cn/spring-boot/features.html#features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables)) | | ϵͳԣSystem properties | շ, kebab , » | ʹ `[ ]` 򶺺ŷֵָı׼б﷨ |
ǽ飬ڿܵ£ӦСдkebabʽ洢 my.person.first-name=Rod
Map

󶨵 Map ʱҪʹһŷţԱ㱣ԭʼ key ֵ keyûб [ ] κηĸ֡- . ַɾ

磬ǽ԰󶨵һ Map<String,String>

Properties

Yaml

my.map.[/key1]=value1
my.map.[/key2]=value2
my.map./key3=value3
YAMLļҪŰʹkeyȷ

Խ󶨵һ Map /key1``/key2 key3 Ϊmapkey бѾ key3 ɾΪûбŰ

󶨵ֵʱ . ļҪ [] ֵöٺ java.lang еͣ Object a.b=c 󶨵 Map<String, String> е . һ {"a.b"="c"} EntryMap κͣ key . Ҫʹŷš 磬 a.b=c 󶨵 Map<String, Object> һ {"a"={"b"="c"} entryMap [a.b]=c һ {"a.b"="c"} entry Map

ӻ

磬Linux shellֻܰĸa z A Z ֣ 0 9 »ַ _ չUnix shellҲôдĸ

Spring Bootɵİ󶨹ΪܵЩƼݡ

Ҫ淶ʽתΪƣѭЩ

  • »ߣ_滻㣨.

  • ɾκۺţ-

  • תΪдĸ

spring.main.log-startup-info һΪ SPRING_MAIN_LOGSTARTUPINFO Ļ

Ҳڰ󶨵бListʱʹá Ҫ󶨵һ ListڱУԪرţӦ»߰

my.service[0].other ʹһΪ MY_SERVICE_0_OTHER Ļ

2.8.7. ϲӵ

Listڶطʱǵ滻list

磬һ MyPojo name description ĬΪ null Ӵ MyProperties б¶һ MyPojo б

Java

Kotlin

@ConfigurationProperties("my")
public class MyProperties {

    private final List<MyPojo> list = new ArrayList<>();

    public List<MyPojo> getList() {
        return this.list;
    }

}

á

Properties

Yaml

my.list[0].name=my name
my.list[0].description=my description
#---
spring.config.activate.on-profile=dev
my.list[0].name=my another name

dev ļδMyProperties.list һ MyPojo Ŀ֮ǰ Ȼ dev ļlist ȻֻһĿname Ϊ my another namedescriptionΪ null òбӵڶ MyPojo ʵҲϲĿ

һ List ڶļбָʱʹþȼǸֻǸ ӡ

Properties

Yaml

my.list[0].name=my name
my.list[0].description=my description
my.list[1].name=another name
my.list[1].description=another description
#---
spring.config.activate.on-profile=dev
my.list[0].name=my another name

ǰУ dev ļǼģMyProperties.list һ MyPojo Ŀname my another namedescription null YAMLŷָбYAMLбȫбݡ

Map ԣôӶԴȡֵа󶨡 ȻڶԴеͬһԣʹþȼǸ Ӵ MyProperties ¶һ Map<String, MyPojo>

Java

Kotlin

@ConfigurationProperties("my")
public class MyProperties {

    private final Map<String, MyPojo> map = new LinkedHashMap<>();

    public Map<String, MyPojo> getMap() {
        return this.map;
    }

}

á

Properties

Yaml

my.map.key1.name=my name 1
my.map.key1.description=my description 1
#---
spring.config.activate.on-profile=dev
my.map.key1.name=dev name 1
my.map.key2.name=dev name 2
my.map.key2.description=dev description 2

dev ļûмMyProperties.map һkeyΪ key1 ĿnameΪ my name 1 descriptionΪ my description 1 Ȼ dev ļmap ĿkeyΪ key1 nameΪ dev name 1descriptionΪ my description 1 key2nameΪ dev name 2descriptionΪ dev description 2

ǰĺϲԴԣļ

2.8.8. ԣPropertiesת

Spring Boot @ConfigurationProperties Beanʱͼⲿapplication propertiesǿƸΪȷ͡ ҪԶתṩһ ConversionService beanBeanΪ conversionService ԶԱ༭ͨ CustomEditorConfigurer beanԶ Converters Beanʹ @ConfigurationPropertiesBinding ע⣩

BeanӦóڵڱģȷ ConversionService ʹõϵ ͨ£Ҫκϵڴʱûȫʼ Զ ConversionService Ҫkeys coercionֻ @ConfigurationPropertiesBinding ޶Զת
תΪ Duration

Spring BootԱʱרŵ֧֡ 㹫һ java.time.Duration ԣapplication propertiesе¸ʽͿá

뿼ӡ

Java

Kotlin

@ConfigurationProperties("my")
public class MyProperties {

    @DurationUnit(ChronoUnit.SECONDS)
    private Duration sessionTimeout = Duration.ofSeconds(30);

    private Duration readTimeout = Duration.ofMillis(1000);

    // getters / setters...

}

Ҫָһ30ĻỰʱ 30 PT30S 30s ǵȼ۵ġ ȡʱΪ500msκһʽָ 500, PT0.5S 500ms.

Ҳʹֵ֧ʱ䵥λ

  • ns

  • us ΢

  • ms

  • s

  • m

  • h Сʱ

  • d

ĬϵλǺ룬ʹ @DurationUnit дʾ

ϲʹù캯󶨣ͬԿԱ¶ʾ

Java

Kotlin

@ConfigurationProperties("my")
public class MyProperties {

    // fields...

    public MyProperties(@DurationUnit(ChronoUnit.SECONDS) @DefaultValue("30s") Duration sessionTimeout,
            @DefaultValue("1000ms") Duration readTimeout) {
        this.sessionTimeout = sessionTimeout;
        this.readTimeout = readTimeout;
    }

    // getters...

}

Ҫһ Long ԣǺ룬ȷ嵥λʹ @DurationUnit ṩһ͸·ͬʱָ֧ḻĸʽ
תΪڼ䣨Period

durationSpring Bootʹ java.time.Period ͡ ¸ʽapplication propertiesʹá

  • һ int ʾʹΪĬϵλָ @PeriodUnit

  • ׼ISO-8601ʽ java.time.Period ʹ

  • һ򵥵ĸʽֵ͵λϵģ 1y3d ʾ13죩

֧м򵥵ĵλʽ

  • y

  • m

  • w

  • d

java.time.Period ʵϴδ洢һݷʽζ 7족
תΪݴСData Sizes

Spring Frameworkһ DataSize ֵֽͣΪλС 㹫һ DataSize ԣapplication propertiesе¸ʽͿá

  • һ long ʾʹֽΪĬϵλָ @DataSizeUnit

  • һ׶ĸʽֵ͵λϵģ10MB ζ10ֽڣ

ӡ

Java

Kotlin

@ConfigurationProperties("my")
public class MyProperties {

    @DataSizeUnit(DataUnit.MEGABYTES)
    private DataSize bufferSize = DataSize.ofMegabytes(2);

    private DataSize sizeThreshold = DataSize.ofBytes(512);

    // getters/setters...

}

Ҫָһ10ֽڣMbĻС 10 10MB ǵȼ۵ġ 256ֽڵĴСֵָΪ 256 256B

ҲʹЩֵ֧ĵλ

  • B ֽ

  • KB KB

  • MB MB

  • GB GB

  • TB TB

Ĭϵλֽڣʹ @DataSizeUnit дʾ

ϲʹù캯󶨣ͬԿԱ¶ʾ

Java

Kotlin

@ConfigurationProperties("my")
public class MyProperties {

    // fields...

    public MyProperties(@DataSizeUnit(DataUnit.MEGABYTES) @DefaultValue("2MB") DataSize bufferSize,
            @DefaultValue("512B") DataSize sizeThreshold) {
        this.bufferSize = bufferSize;
        this.sizeThreshold = sizeThreshold;
    }

    // getters...

}

һ Long ԣȷ嵥λʹ @DataSizeUnitֽڡ ṩһ͸·ͬʱָ֧ḻĸʽ

2.8.9. @ConfigurationProperties У

ֻҪʹSpring @Validated ע⣬Spring Bootͻ᳢֤ @ConfigurationProperties ࡣ ֱʹJSR-303 jakarta.validation Լע⡣ Ҫһ㣬ȷclasspathһݵJSR-303ʵ֣ȻԼעӵֶУʾ

Java

Kotlin

@ConfigurationProperties("my.service")
@Validated
public class MyProperties {

    @NotNull
    private InetAddress remoteAddress;

    // getters/setters...

}

Ҳͨ configuration properties @Bean ע @Validated ֤

ΪȷΪǶ׵Դ֤ʹûҵԣصֶα @Valid ע͡ ӽǰ MyProperties Ļϡ

Java

Kotlin

@ConfigurationProperties("my.service")
@Validated
public class MyProperties {

    @NotNull
    private InetAddress remoteAddress;

    @Valid
    private final Security security = new Security();

    // getters/setters...

    public static class Security {

        @NotEmpty
        private String username;

        // getters/setters...

    }

}

ҲͨһΪ configurationPropertiesValidator beanһԶSpring Validator @Bean ӦñΪ static ֤Ӧóڵڴģ @Bean Ϊ̬BeanĴҪʵ @Configuration ࡣ Աʵκ⡣

spring-boot-actuator ģһ¶ @ConfigurationProperties Bean Ķ˵㡣 ͨ /actuator/configprops ʹӦJMX˵㡣 "

2.8.10. @ConfigurationProperties vs. @Value

@Value עһĵܣṩͰȫͬĹܡ ±ܽ @ConfigurationProperties @Value ֵ֧Ĺܡ

<colgroup><col><col><col></colgroup> | | `@ConfigurationProperties` | `@Value` | | --- | --- | --- | | [ɰ](https://springdoc.cn/spring-boot/features.html#features.external-config.typesafe-configuration-properties.relaxed-binding) | Yes | ( [ע](https://springdoc.cn/spring-boot/features.html#features.external-config.typesafe-configuration-properties.vs-value-annotation.note)) | | [֧ Meta-data](https://springdoc.cn/spring-boot/configuration-metadata.html#appendix.configuration-metadata) | Yes | No | | `SpEL` ʽ | No | Yes |
ȷʵʹ @ValueǽʹƵĹ淶ʽʹСдĸkebab-caseơ ⽫Spring Bootʹ ɰ @ConfigurationProperties ʱͬ߼磬@Value("${demo.item-price}") application.properties ļлȡ demo.item-price demo.itemPrice ʽԼϵͳлȡ DEMO_ITEMPRICE @Value("${demo.itemPrice}")demo.item-price DEMO_ITEMPRICE ᱻǡ

ΪԼһüǽ㽫Ƿһ @ConfigurationProperties עPOJOС ΪṩṹġͰȫĶԽע뵽ԼbeanС

Ӧapplication property ļ SpEL ʽڽЩļenvironmentʱᱻ Ȼ @Value дһ SpEL ʽ Ӧóļֵһ SpEL ʽڱ @Value ʱ