当前位置:网站首页>@The difference between configurationproperties and @value
@The difference between configurationproperties and @value
2022-07-01 02:02:00 【It midsummer fruit】
Catalog
2 @ConfigurationProperties and @value The difference between
1 Preface
In normal development , We will configure a large number of parameters in application.properties perhaps application.yml In file , adopt @ConfigurationProperties Note or @value Annotation can easily get these values .
2 @ConfigurationProperties and @value The difference between
The two annotation buckets can read the properties in the configuration file and bind to javaBean in , But the two have the following differences
1) Use different positions
@ConfigurationProperties: Marked on JavaBean On the class name of ;
@Value: Marked on JavaBean On the properties of .
2) function
@ConfigurationProperties: Used for configuration in batch binding configuration file ;
@Value: You can only specify the binding location one by one , The binding granularity is smaller
3) Loose binding supports different
@ConfigurationProperties: Support for loose binding , For example, entity class Person One of the attributes in is username, Then the attribute name in the configuration file supports the following writing :person.username、person_name、person.user_name、PERSON_USER_NAME
@Value: Loose binding is not supported
4) Complex type encapsulation
@ConfigurationProperties: Supports all types of encapsulation , for example Map、List、Set And objects
@Value: Only encapsulation of basic data types is supported , for example : character string 、 Boolean value 、 Integer and other types
5) Different application scenarios , There is no obvious difference between the two , They are only suitable for different scenarios . If you just get a value in the configuration file , It is recommended to use @Value annotation ; If you specially write a JavaBean To map with the configuration file , It is recommended to use @ConfigurationProperties annotation .
3 usage
3.1 @ConfigurationProperties
Entity class :
package com.liubujun.springdataelasticsearch.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author: liubujun
* @Date: 2022/6/30 13:57
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String username;
private Integer age;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"username='" + username + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
The configuration file :
person.username=Tony teacher
person.age=21
person.address= The global village Test class :
@Autowired
private Person person;
@Test
public void test(){
System.out.println(" full name :"+person.getUsername()+"、 Age :"+person.getAge()+"、 Address :"+person.getAddress());
}Running results :

From the running results, we can find that we can successfully obtain relevant values from the configuration file .
Be careful :@ConfigurationProperties Support for loose binding
Change the configuration file to :
person.user_name=Tony teacher
person.age=21
person.address= The global village The test found that the value is still obtained normally :

Be careful : @ConfigurationProperties Support complex type encapsulation
Change the configuration file to :
person.user_name=Tony teacher
person.age=21
person.address= The global village
person.email[0][email protected]
person.email[1][email protected]
person.email[2][email protected]Add a field to the entity class to modify it :
@Component
@ConfigurationProperties(value = "person")
public class Person {
private String username;
private Integer age;
private String address;
private List<String> email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<String> getEmail() {
return email;
}
public void setEmail(List<String> email) {
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"username='" + username + '\'' +
", age=" + age +
", address='" + address + '\'' +
", email=" + email +
'}';
}
}
Test class :
@Autowired
private Person person;
@Test
public void test(){
System.out.println(" full name :"+person.getUsername()+"、 Age :"+person.getAge()+"、 Address :"+person.getAddress()+"、email:"+person.getEmail());
}
result :

3.2 @Value
The entity classes are as follows : Other configurations remain unchanged
@Component
public class Person {
@Value("${person_username}")
private String username;
@Value("${person.age}")
private Integer age;
@Value("${person.address}")
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"username='" + username + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
Test the normal output :

Be careful :@Value Loose binding is not supported , If you change the configuration file to the following :
person.user_name=Tony teacher
person.age=21
person.address= The global village The test found that “username” Value , The error information is as follows :
Error creating bean with name 'person': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person_username' in value "${person_username}"Be careful :@Value Complex type encapsulation is not supported , Add an entity class List Type field
@Component
public class Person {
@Value("${person.username}")
private String username;
@Value("${person.age}")
private Integer age;
@Value("${person.address}")
private String address;
@Value("${person.email}")
private List<String> email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<String> getEmail() {
return email;
}
public void setEmail(List<String> email) {
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"username='" + username + '\'' +
", age=" + age +
", address='" + address + '\'' +
", email=" + email +
'}';
}
}The configuration file is modified as follows :
person.user_name=Tony teacher
person.age=21
person.address= The global village
person.email[0][email protected]
person.email[1][email protected]
person.email[2][email protected]Test class :
@Autowired
private Person person;
@Test
public void test(){
System.out.println(" full name :"+person.getUsername()+"、 Age :"+person.getAge()+"、 Address :"+person.getAddress()+"、email:"+person.getEmail());
}
An error is found after running :
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person.email' in value "${person.email}"But if you get one of these values, there will be no problem :

Running results :

4 Specify profile
In actual development , There is a lot of content that needs configuration management , It is impossible to put all the information in the same configuration file , This is neither safe nor convenient for maintenance , We can SpringBoot Irrelevant configurations are put into other configuration files separately , When you need these JavaBean It can be used on ,SpringBoot Provides @PropertySource annotation .
Create a new file :

Before application.properties Paste the contents of the file into the file .
Entity class plus corresponding path :
After the test, it is found that the value can still be obtained normally

边栏推荐
- Log4j2 ThreadContext日志链路追踪
- (translation) use eyebrow shaped text to improve Title click through rate
- SWT/ANR问题--StorageManagerService卡住
- FL studio20.9 fruit software advanced Chinese edition electronic music arrangement
- 软件测试的可持续发展,必须要学会敲代码?
- (总结一)Halcon基础之寻找目标特征+转正
- PHP array splicing MySQL in statement
- [content of content type request header]
- Handsontable數據網格組件
- MYSQL 数据库查看磁盘占用情况
猜你喜欢

Batch import of Excel data in applet

远程办公如何保持高效协同,实现项目稳定增长 |社区征文

Calculate special bonus

Video tutorial | Chang'an chain launched a series of video tutorial collections (Introduction)

数据探索电商平台用户行为流失分析

Selenium classic interview question - multi window switching solution

CorelDRAW 2022 Chinese Simplified 64 bit direct download

QML控件类型:ToolTip

【JS】【掘金】获取关注了里不在关注者里的人

LabVIEW计算相机图像传感器分辨率以及镜头焦距
随机推荐
When facing the industrial Internet, they even use the ways and methods of consuming the Internet to land and practice the industrial Internet
int和位数组互转
Ks009 implementation of pet management system based on SSH
数据探索电商平台用户行为流失分析
Log4j2 ThreadContext日志链路追踪
Some essential differences
Leetcode 面试题 17.10. 主要元素
P6773 [noi2020] destiny (DP, segment tree merging)
SWT/ANR问题--Binder Stuck
Video tutorial | Chang'an chain launched a series of video tutorial collections (Introduction)
思特奇加入openGauss开源社区,共同推动数据库产业生态发展
【毕业季·进击的技术er】--毕业到工作小结
CorelDRAW 2022中文精简64位直装版下载
QML control type: tooltip
开源基础软件公司,寻找一起创造未来的你(API7.ai)
After working for 6 years, let's take stock of the golden rule of the workplace where workers mix up
小程序中实现excel数据的批量导入
SWT/ANR问题--Native方法执行时间过长导致SWT
2022年最新csdn涨薪技术栈-app自动化测试概述
软件测试的可持续发展,必须要学会敲代码?