Spring boot external configuration of the most complete analysis!

Tian Qiao Ba Xia 2020-11-10 15:38:16
spring boot external configuration complete


SpringBoot Configuration resolution in 【Externalized Configuration】

The main point of this article is

  • Introduce the priority of various configuration methods .
  • Introduce various external configuration methods .
  • Introduce yaml Format and principle of .
  • Describes how to bind and test type safe property configuration .
  • Introduce @ConfigurationProperties And @Value The difference between .

One 、SpringBoot The introduction and function order of external configuration in official documents

SpringBoot Support multiple external configurations , In order to facilitate developers in different environments , Use the same set of application code . There are many ways to externalize configuration :properties file ,yaml file ,Environment Variables, command line parameters, etc .

Attribute values of externalized configuration can be accessed through @Value Annotations are automatically injected , It can also be passed Spring Of Environment Abstract access , It can also be done through @ConfigurationProperties Annotations are bound to structured objects .

SpringBoot Support many kinds of external configuration , We will introduce to you later . before this , We have to know that if multiple configurations appear at the same time , It must take effect in a certain order . The following rules :

  1. devtool be in active In the state of ,$HOME/.config/spring-boot In the directory Devtool Global configuration .
  2. In the test @TestPropertySource annotation .
  3. In the test @SpringBootTest#properties Annotation features .
  4. Command line arguments .
  5. SPRING_APPLICATION_JSON Properties in ( Inline in environment variables or system properties JSON The embedded ).
  6. ServletConfig Initialize parameters .
  7. ServletContext Initialize parameters .
  8. java:comp/env Inside JNDI attribute
  9. JVM System attribute System.getProperties().
  10. Operating system environment variables
  11. Only with random.* Attribute RandomValuePropertySource .
  12. Outside of the app application-{profile}.properties perhaps application-{profile}.yml file
  13. Packaged in an application application-{profile}.properties perhaps application-{profile}.yml file
  14. Outside of the app application.properties perhaps appliaction.yml file
  15. Packaged in an application application.properties perhaps appliaction.yml file
  16. @Configuration On the class @PropertySource annotation , We need to pay attention to , stay ApplicationContext Before refreshing , The properties in this class will not be added to the environment , image logging.*,spring.main.* Something like that , It's too late to configure here .
  17. The default attribute ( adopt SpringApplication.setDefaultProperties Appoint ).

Here the list is sorted by group priority , in other words , Any property set in a high priority attribute source will override the same attribute with a lower priority , Columns like the command-line properties we mentioned above override application.properties Properties of .

Let's give you an example :

If in application.properties Set in name= God, jojobasha , At this point, I use the command line to set java -jar hyh.jar --author.name=summerday, The final name The value will be summerday, Because command line properties have a higher priority .

Two 、 Various external configurations

1、 Random value configuration

In profile ${random} Can be used to generate various types of random values , This simplifies the trouble of code generation , for example Generate int value 、long Value or string character string . The principle is ,RandomValuePropertySource Class overridden getProperty Method , Judge by random. After the prefix , It was properly handled .

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.lessThanTen=${random.int(10)}
my.inRange=${random.int[1024,65536]}

2、 Command line parameter configuration

By default ,SpringApplication Set all command line option parameters 【 With -- Parameters at the beginning , Such as --server.port=9000】 Convert to properties , And add them to SpringEnvironment in , The configuration of command-line properties always takes precedence over other attribute configurations .

If you don't want to add command line properties to Environment in , have access to SpringApplication.setAddCommandLineProperties(false) Disable it .

$ java -jar app.jar --debug=true # Turn on debug Pattern , This is in application.properties The document defines debug=true It's the same

3、 Property file configuration

This part of property file configuration is familiar to us , We are creating... Quickly SpringBoot When the project is , The default will be resources Create one in the directory application.properties file .SpringApplication Will load the configuration properties from the configuration file , And finally join in Spring Of Environment in . except resources Under the table of contents , There are other paths ,SpringBoot By default, it supports storing configuration files .

  1. In the root directory of the current project /config Under the table of contents
  2. The root directory of the current project
  3. resources In the catalog /config Under the table of contents
  4. resources Under the table of contents

The four above , The priority goes down from top to bottom , in other words , If it appears at the same time , The properties configured above will override the following .

About profiles ,properties and yaml The files can meet the needs of the configuration .

Of course , These configurations are flexible , If you don't like the default profile name or the default path , You can configure it :

$ java -jar myproject.jar --spring.config.name=myproject
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

4、 Appoint profile attribute

Usually , The applications we develop need to be deployed to different environments , The configuration of attributes naturally needs to be different . If you replace the configuration file every time you publish , Too much trouble .SpringBoot This is facilitated by the multi environment configuration of . The specific methods are as follows :

We said before when we introduced the priority of various configurations ,application-{profile}.properties perhaps application-{profile}.yml file Has a higher priority than application.properties or application.yml To configure , there profile It's the environmental identity we define :

We are resource Create three files in the directory :

  • application.properties: Default configuration ,default.
  • application-dev.properties: development environment ,dev.
  • application-prod.properties: Production environment ,prod.

We can do this by specifying spring.profiles.active Property to activate the corresponding configuration environment :

spring.profiles.active=dev

Or use the configuration form of command line parameters :

$ java -jar hyh.jar --spring.profiles.active=dev

without profile The specified file is in profile The configuration properties of the specified file are defined at the same time , The specified profile Configuration priority .

5、 Use placeholders

In the use of application.properties When it's worth , They're going to start from Environment Get the value , That means , You can refer to previously defined values , For example, reference to system properties . The specific methods are as follows :

name= God, jojobasha
description=${name} is my name

6、 Encrypt properties

Spring Boot Does not provide any built-in support for encrypted property values , however , It provides modify Spring Values in the environment The required hook point . We can do that by implementing EnvironmentPostProcessor Interface manipulates before the application starts Environment.

You can refer to howto.html, See how to use it .

7、 Use YAML Instead of properties

YAML yes JSON Superset , It's a kind of Specifies a convenient format for the hierarchy configuration data , We use properties A comparison of the documents shows that :

#properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
my.servers[0]=www.hyh.com
my.servers[1]=www.yhy.com
# yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
username: root
password: 123456
my:
server:
- www.hyh.com
- www.yhy.com

As long as you have SnakeYAML library ,SpringApplication Class will automatically support YAML As a way to configure properties .SpringBoot In the project spring-boot-starter Related class libraries have been provided :org.yaml.snakeyaml, therefore SpringBoot Nature supports this way of configuration .

About yaml File format , Please refer to the official documents :Using YAML Instead of Properties

8、 Type safe property configuration

It's about passing @Value("${property}") Annotations to inject configuration can be cumbersome , Especially when multiple attributes are essentially hierarchical .SpringBoot It provides a solution : Let strong type bean Manage and verify your configuration .

Let's look directly at the specific use of the bell :

@ConfigurationPropertie Define a binding configuration of JavaBean

  1. Use the default constructor +getter and setter Inject
@ConfigurationProperties("acme")
public class AcmeProperties {
private boolean enabled; //acme.enabled The default is false
private InetAddress remoteAddress;// acme.remote-address It can be downloaded from String The type of conversion
private final Security security = new Security();
//.. Omit getter and setter Method
public static class Security {
private String username; // acme.security.username
private String password; // acme.security.password
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));// acme.security.roles
//.. Omit getter setter Method
}
}

This depends on the default null constructor , adopt getter and setter Method assignment , therefore getter and setter Methods are necessary , It does not support binding of static properties .

If nested pojo Property has been initialized with value : private final Security security = new Security(); No need setter Method . If you want the binder to create instances dynamically using its default constructor , You need to setter.

  1. adopt @ContructorBinding Annotations use constructor binding :
@ConstructorBinding // Annotations are bound with constructors
@ConfigurationProperties("acme")
public class AcmeProperties {
private final Security security;
private final boolean enabled;
private final InetAddress remoteAddress;
public AcmeProperties(boolean enabled, InetAddress remoteAddress, Security security) {
this.enabled = enabled;
this.remoteAddress = remoteAddress;
this.security = security;
}
//.. Omit getter Method
@ToString
public static class Security {
private final String username;
private final String password;
private final List<String> roles;
public Security(String username, String password,
@DefaultValue("USER") List<String> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
}
//.. Omit getter Method
}

If not configured Security Instance attributes , So the final result :Security=null. If we want to Security={username=null,password=null,roles=[USER]}, Can be in Security Add up @DefaultValue.public AcmeProperties(boolean enabled, InetAddress remoteAddress, @DefaultValue Security security)

adopt @EnableConfigurationProperties register

It's already defined JavaBean, And bind with configuration properties , Then you need to register these bean. We usually use @Component or @Bean,@Import load bean It's not advisable here ,SpringBoot Provides a solution : Use @EnableConfigurationProperties, We can specify the configured classes one by one , It can also be configured as a component scan .

@SpringBootApplication
@EnableConfigurationProperties({HyhConfigurationProperties.class, MyProperties.class,AcmeProperties.class})
public class SpringBootProfileApplication {
}
@SpringBootApplication
@ConfigurationPropertiesScan({"com.hyh.config"})
public class SpringBootProfileApplication {
}

To configure yaml file

acme:
remote-address: 192.168.1.1
security:
username: admin
roles:
- USER
- ADMIN

Inject properties, test

@Configuration
public class Application implements CommandLineRunner {
@Autowired
private AcmeProperties acmeProperties;
@Override
public void run(String... args) throws Exception {
System.out.println(acmeProperties);
}
}
// Output :
AcmeProperties(security=AcmeProperties.Security(username=admin, password=null, roles=[USER, ADMIN]), enabled=false, remoteAddress=/192.168.1.1)

Loose binding

SpringBoot Adopt loose rules Environment and @ConfigurationProperties mark bean The matching of . Such as :

@ConfigurationProperties(prefix="acme.my-project.person")
public class OwnerProperties {
private String firstName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

The attribute names in the following table can match :

Property Note
acme.my-project.person.first-name Kebab case, which is recommended for use in .properties and .yml files.
acme.myProject.person.firstName Standard camel case syntax.
acme.my_project.person.first_name Underscore notation, which is an alternative format for use in .properties and .yml files.
ACME_MYPROJECT_PERSON_FIRSTNAME Upper case format, which is recommended when using system environment variables.

@ConfigurationProperties In the annotations prefix The value must be kebab case Formal , With - For the separator .

Spring The official advice , Properties as much as possible lower-case kebab In the form of :my.property-name=acme

Map How to bind

Bound to the Map Attribute , If key contain Lower case alphanumeric characters or - Any other characters other than , You need to use square brackets around key, In order to keep the original value . If the key is not [] Surround , Then all non alphanumeric or - The characters of will be deleted . as follows :

hyh:
username: God, jojobasha
password: 123456
map:
"[/key1]": value1 # Surround with quotation marks [], use [] Surround key
/key3: value3
key-4: value4
key/5: value5
# result :"map":{/key1=value1,key5=value5, key-4=value4, key3=value3}

How environment variables bind

Follow three principles :

  1. hold . Change to underline _.
  2. remove -.
  3. Small to capital .

Such as :spring.main.log-startup-info To :SPRING_MAIN_LOGSTARTUPINFO,my.acme[0].other To MY_ACME_0_OTHER.

9、 Complex type

Previous introduction yml file , This paper introduces the simple binding of array form or value ,SpringBoot It also supports binding of complex types .

merge:
list:
- name: God, jojobasha
desc: Handsome
- name: tqbx
desc: It's so handsome
map:
key1:
name: summerday
desc: handsome!
key2:
name: summer
@ToString
@ConfigurationProperties(prefix = "merge")
public class MergeProperties {
private final List<User> list = new ArrayList<>();
private final Map<String,User> map = new HashMap<>();
public List<User> getList() {
return list;
}
public Map<String, User> getMap() {
return map;
}
}

The final output :

MergeProperties(
list=[User(name= God, jojobasha , desc= Handsome ),
User(name=tqbx, desc= It's so handsome )],
map={key1=User(name=summerday, desc=handsome!),
key2=User(name=summer, desc=null)}a
)

10、 Parameter checking

Yes @ConfigurationProperties Class uses Spring Of @Valid When the annotation ,Spring Boot They try to verify it .

You can use it directly on the configuration class JSR-303 javax.validation constraint annotation . The premise of this is , Your classpath has compatible JSR-303 Realization :

 <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.18.Final</version>
</dependency>

Then add the constraint annotation to the field , as follows :

@Data
@Validated
@ConfigurationProperties(prefix = "validate")
public class ValidateProperties {
@NotNull
private String name;
@Valid
private final SubProperties subProperties = new SubProperties();
@Data
public static class SubProperties {
@Min(value = 10,message = " The youngest is 10")
public Integer age;
}
}

The configuration is as follows :

validate:
name: hyh
sub-properties:
age: 5

give the result as follows :

Description:
Binding to target org.springframework.boot.context.properties.bind.BindException:
Failed to bind properties under 'validate' to com.hyh.config.ValidateProperties failed:
Property: validate.sub-properties.age
Value: 5
Origin: class path resource [application.yml]:47:10
Reason: The youngest is 10
Action:
Update your application's configuration

3、 ... and 、@ConfigurationProperties And @Value The difference between

@Value Annotation is a core container function , It is not provided and type-safe Configuration properties related functions , The following table summarizes the functions supported by each :

Feature @ConfigurationProperties @Value
Loose binding Yes Limited (see note below)
Metadata support Yes No
SpEL expression No Yes

The official advice :

  • If you define a set of configurations for your components , It is recommended to use @ConfigurationProperties and POJO binding , This provides structured and type safe objects .
  • If you have to use it hard @Value, It is recommended to use kebab-case form , Such as @Value(" ${demo.item-price}")

Source download

The content of this article is a summary of excellent blogs and official documents , The address of the original text has been marked in the reference section of the text . Last , All the code samples in this article have been uploaded to Gitee:https://gitee.com/tqbx/springboot-samples-learn, There are other SpringBoot The integration of oh .

Reference reading

版权声明
本文为[Tian Qiao Ba Xia]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云