docs/Spring全家桶/SpringBoot/SpringBoot的配置文件管理.md
ΪʵֿٴͿĿSpringbootܴspringbootĿԽĿֱӴjarУԼװTomcatһַݵIJʽ
Ŀķʽһjar𣬼ļ͵jarͻ
һĿйУҪĶļĻҪ´
ĿҪͬһ̨ʱԵjarͬĵĿjar100Mܾռ99M˷Դ˷ԼĿЧʡ
ĿļȡjarͳһĿЧֽԼ˷ĴģͬʱĿάҲǷdzģĶļ·Ϳˣ¹
Ǿʵַ
- 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ȼߵλҵãôȼ͵
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
#!/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Ŀ״̬
Spring Boot㽫ⲿͿڲͬĻʹͬӦó롣 ʹøⲿԴJava properties ļYAMLļв
ֵͨʹ @Value עֱעBeanҲͨSpring Environment ʣͨ @ConfigurationProperties
Spring Boot ʹһdzر PropertySource ˳ּдֵ property source ԸǰԴжֵ ˳ǡ
Ĭԣͨ SpringApplication.setDefaultProperties ָ
@Configuration ϵ @PropertySource ע⡣ע⣬Դֱapplication contextˢʱŻᱻӵСijЩ˵Ѿ̫ˣ logging.* spring.main.* ˢ¿ʼǰѾȡˡ
ݣ application.properties ļ
RandomValuePropertySourceֻ random.* ԡ
ϵͳ
Java System properties (System.getProperties()).
java:comp/env е JNDI ԡ
ServletContext init parameters.
ServletConfig init parameters.
SPRING_APPLICATION_JSON ԣǶ뻷ϵͳеJSON
в
ڲе properties ԡ @SpringBootTest ͲעпãڲӦóһضƬ
devtoolsڻ״̬ʱ$HOME/.config/spring-boot Ŀ¼µDevtoolsȫ
ļ˳ǡ
jarдApplication propertiesapplication.properties YAML
jarд ض Profile application propertiesapplication-{profile}.properties YAML
jar֮Application propertiesԣapplication.propertiesYAML
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áʹ˵ֵ "" ֡ |
|---|
Ĭ£SpringApplication Ὣκѡ -- ͷIJ --server.port=9000 תΪ property ӵSpring Environment С ǰڻļԴ
㲻ϣԱӵ Environment Уͨ SpringApplication.setAddCommandLineProperties(false) ǡ
ϵͳƣζЩƲʹá Ϊ˰⣬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 ֵԵͽԴԡ |
|---|
ӦóʱSpring BootԶλҵ application.properties application.yaml ļ
classpath
classpath ·
classpath µ /config
ǰĿ¼
ǰĿ¼
ǰĿ¼µ config/ Ŀ¼
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/ ǵλü¡
optional:classpath:custom-config/
optional:file:./custom-config/
ϲӶλã滻ǣʹ spring.config.extra-location ӸλüصԿԸĬλõԡ 磬 spring.config.extra-location Ϊ optional:classpath:/custom-config/,optional:file:./custom-config/ ǵλü¡
optional:classpath:/;optional:classpath:/config/
optional:file:./;optional:file:./config/;optional:file:./config/*/
optional:classpath:custom-config/
optional:file:./custom-config/
һļָĬֵȻһļѡԵظЩֵ һĬλõ application.properties spring.config.name ѡbasenameΪӦóṩĬֵ ȻЩĬֵʱλһԶλõIJͬļǡ
ʹûϵͳԣϵͳʹþָļʹ»ߴ棨磬 SPRING_CONFIG_NAME spring.config.name μӻ ˽顣 |
|---|
ӦóservletӦ÷УôJNDIԣ java:comp/env УservletijʼԴ滷ϵͳԣ֮һ |
|---|
Ĭ£ָλòʱ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
һļλһ·а * ַͱΪһͨλá ͨڼʱչˣֱӵĿ¼Ҳ顣 ͨλ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: λʹͨ |
|---|
application ļSpring Bootʹ application-{profile} profileضļ 磬ӦóΪ prod ļspring.profiles.active=prodʹYAMLļô application.yml application-prod.yml ǡ
ضļ(profiles) application.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 ԡ
| ļֻһΡ Ѿֱһļضļôᱻڶε롣 |
|---|
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 塣 |
|---|
Щƽ̨Ϊװļvolume mounted filesļչ ҪЩչļҪSpring BootһʾԱ֪μǡ ͨչʾڷһ㡣
磬һ /etc/config/myconfig ļϣyamlʽ롣 ķ application.properties е
Properties
Yaml
spring.config.import=file:/etc/config/myconfig[.yaml]
ƽ̨KubernetesӦóʱ㾭Ҫȡƽ̨ṩֵ ڴĿIJټȱ㣬رֵ secret ġ
Ϊƽ̨㽫ӳ䵽صݾ 磬Kubernetes Ծ ConfigMaps Secrets
ʹֳ volume ģʽ
һļһԣͨдYAML
ļдһĿ¼УļΪ 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/
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_ķ |
|---|
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 עء |
|---|
ʱֻ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
Spring BootûΪֵṩκ֧֣ṩHookmSpring Environment аֵ EnvironmentPostProcessor ӿӦóǰ Environment μhowto.html˽顣
Ҫһְȫķʽ洢ƾ֤룬 Spring Cloud Vault Ŀṩ˶ HashiCorp Vaultд洢ⲿõ֧֡
YAML JSONijֲָݵķʽ ֻҪclasspath SnakeYAML ⣬SpringApplication ͻԶ֧YAMLΪpropertiesƷ
ʹ StarterSnakeYAML spring-boot-starter Զṩ |
|---|
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 ļ |
|---|
Spring Frameworkṩ࣬YAMLĵ YamlPropertiesFactoryBean YAMLΪ Properties أYamlMapFactoryBean YAMLΪ Map ء
YAMLΪSpring PropertySource Ҳʹ YamlPropertySourceLoader ࡣ
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,max ṩ maxô value Сֵ max ֵռ
Spring Boot֧Ϊһǰ ϵͳвͬҪSpring BootӦóͺá ϵͳԵǰֱ SpringApplication á
磬㽫ǰΪ input remote.timeout ϵͳҲΪ input.remote.timeout
ʹ @Value("${property}") עעʱ鷳رǵҪԻǷֲġ Spring BootṩһִԵǿ͵Bean֤Ӧóá
μ@Value Ͱȫ֮ |
|---|
ʾһ˱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ΪκضĹ캯ΪԶʵֻDZJava Beanԣֶ֧Ծ̬Եİ |
|---|
һڵӿòɱķʽдʾ
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 |
|---|
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
÷ʽ 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ԵġԶȫܡ ¼ |
|---|
ʹ @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 ӡ
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 |
|---|
ǽ飬ڿܵ£ӦСдkebabʽ洢 my.person.first-name=Rod |
|---|
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 Ļ
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
| ǰĺϲԴԣļ |
|---|
Spring Boot @ConfigurationProperties Beanʱͼⲿapplication propertiesǿƸΪȷ͡ ҪԶתṩһ ConversionService beanBeanΪ conversionService ԶԱ༭ͨ CustomEditorConfigurer beanԶ Converters Beanʹ @ConfigurationPropertiesBinding ע⣩
BeanӦóڵڱģȷ ConversionService ʹõϵ ͨ£Ҫκϵڴʱûȫʼ Զ ConversionService Ҫkeys coercionֻ @ConfigurationPropertiesBinding Զת |
|---|
Spring BootԱʱרŵ֧֡ 㹫һ java.time.Duration ԣapplication propertiesе¸ʽͿá
ͨ long ʹúΪĬϵλָ @DurationUnit
ISO-8601ʽ java.time.Duration ʹ
һĸʽֵ͵λϵģ10s ʾ10룩
뿼ӡ
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 ṩһ·ͬʱָ֧ḻĸʽ |
|---|
durationSpring Bootʹ java.time.Period ͡ ¸ʽapplication propertiesʹá
һ int ʾʹΪĬϵλָ @PeriodUnit
ISO-8601ʽ java.time.Period ʹ
һĸʽֵ͵λϵģ 1y3d ʾ13죩
֧мĵλʽ
y
m
w
d
java.time.Period ʵϴδ洢һݷʽζ 7족 |
|---|
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ֽڡ ṩһ·ͬʱָ֧ḻĸʽ |
|---|
ֻҪʹ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˵㡣 ""֡ |
|---|
@Value עһĵܣṩͰȫͬĹܡ ±ܽ @ConfigurationProperties @Value ֵ֧Ĺܡ
ȷʵʹ @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 ʱ