当前位置:网站首页>@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

边栏推荐
- (translation) use eyebrow shaped text to improve Title click through rate
- LabVIEW计算相机图像传感器分辨率以及镜头焦距
- RocketQA:通过跨批次负采样(cross-batch negatives)、去噪的强负例采样(denoised hard negative sampling)与数据增强(data augment
- 7-2 拼题A打卡奖励 dp
- SWT/ANR问题--ANR/JE引发SWT
- URL和URI
- PHP通过第三方插件爬取数据
- 数学知识:求组合数 III—求组合数
- SQL语句关联表 如何添加关联表的条件 [需要null值或不需要null值]
- Handsontable數據網格組件
猜你喜欢

(translation) use eyebrow shaped text to improve Title click through rate

Ernie-gram, 显式、完备的 n-gram 掩码语言模型,实现了显式的 n-gram 语义单元知识建模。

思特奇加入openGauss开源社区,共同推动数据库产业生态发展

Selenium classic interview question - multi window switching solution

机器学习10-信念贝叶斯分类器

工作八年的程序员,却拿着毕业三年的工资,再不开窍就真晚了...

3500字归纳总结:一名合格的软件测试工程师需要掌握的技能大全

Selenium经典面试题-多窗口切换解决方案

运算符重载的初识

测试必备工具—Postman实战教程
随机推荐
PHP数组拼接MySQL的in语句
House change for agricultural products? "Disguised" house purchase subsidy!
Composants de la grille de données portatifs
CorelDRAW 2022中文精简64位直装版下载
FL Studio20.9水果软件高级中文版电音编曲
Alphabet-Rearrange-Inator 3000(字典树自定义排序)
Short message sending solution in medical his industry
Sitge joined the opengauss open source community to jointly promote the ecological development of the database industry
AS400 大廠面試
数学知识:求组合数 IV—求组合数
[无线通信基础-15]:图解移动通信技术与应用发展-3- 数字通信2G GSM、CDMA、3G WDCMA/CDMA200/TD-SCDMA、4G LTE、5G NR概述
Objects and object variables
(总结一)Halcon基础之寻找目标特征+转正
机器学习10-信念贝叶斯分类器
Laravel event & subscription
Static domain and static method
[proteus simulation] Arduino UNO +74c922 keyboard decoding drive 4x4 matrix keyboard
运算符重载的初识
3500 word summary: a complete set of skills that a qualified software testing engineer needs to master
SWT/ANR问题--AMS/WMS