当前位置:网站首页>@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
边栏推荐
- AS400 大廠面試
- 思特奇加入openGauss开源社区,共同推动数据库产业生态发展
- Alphabet rearrange inator 3000 (dictionary tree custom sorting)
- 小程序中实现excel数据的批量导入
- Windows quick add boot entry
- Mathematical knowledge: finding combinatorial number III - finding combinatorial number
- VirtualBox 安装增强功能
- AS400 entretien d'usine
- 远程办公如何保持高效协同,实现项目稳定增长 |社区征文
- QT web development - VIDEO - Notes
猜你喜欢
Machine learning 10 belief Bayesian classifier
After working for 6 years, let's take stock of the golden rule of the workplace where workers mix up
【2022年】江西省研究生数学建模方案、代码
Pytorch —— 基础指北_贰 高中生都能看懂的[反向传播和梯度下降]
7-2 拼题A打卡奖励 dp
VirtualBox 安装增强功能
FL Studio20.9水果软件高级中文版电音编曲
PHP crawls data through third-party plug-ins
工作八年的程序员,却拿着毕业三年的工资,再不开窍就真晚了...
Ernie-gram, 显式、完备的 n-gram 掩码语言模型,实现了显式的 n-gram 语义单元知识建模。
随机推荐
FL studio20.9 fruit software advanced Chinese edition electronic music arrangement
Laravel event & subscription
Live shopping mall source code, realize left-right linkage of commodity classification pages
[proteus simulation] Arduino UNO +74c922 keyboard decoding drive 4x4 matrix keyboard
Upstream and downstream in software development
Fast understanding of forward proxy and reverse proxy
Objects and object variables
With regard to the white box test, you have to master these skills~
KS009基于SSH实现宠物管理系统
如何选择券商?另外,手机开户安全么?
Handsontable data grid component
How does the property send a text message to the owner?
SWT/ANR问题--StorageManagerService卡住
Sitge joined the opengauss open source community to jointly promote the ecological development of the database industry
URL和URI
[无线通信基础-15]:图解移动通信技术与应用发展-3- 数字通信2G GSM、CDMA、3G WDCMA/CDMA200/TD-SCDMA、4G LTE、5G NR概述
[JS adds attributes to elements: setAttribute; classlist.remove; classlist.add;]
Use of laravel carbon time processing class
Ks009 implementation of pet management system based on SSH
AS400 大廠面試