利用@Value注解為bean的屬性賦值方法總結(jié)
1.@Value注解
@Value注解的源碼,如下所示
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value();
}
從@Value注解的源碼中可以看出,@Value注解可以標(biāo)注在字段、方法、參數(shù)以及注解上,而且在程序運(yùn)行期間生效
2.@Value注解的用法
2.1.不通過配置文件注入屬性的情況
通過@Value注解將外部的值動(dòng)態(tài)注入到bean的屬性中,一般有如下這幾種情況
- 注入普通字符串
@Value("liqb")
private String name; // 注入普通字符串
- 注入操作系統(tǒng)屬性
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; // 注入操作系統(tǒng)屬性
- 注入SpEL表達(dá)式結(jié)果
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //注入SpEL表達(dá)式結(jié)果
- 注入其他bean中屬性的值
@Value("#{person.name}")
private String username; // 注入其他bean中屬性的值,即注入person對(duì)象的name屬性中的值
- 注入文件資源
@Value("classpath:/config.properties")
private Resource resourceFile; // 注入文件資源
- 注入U(xiǎn)RL資源
@Value("http://www.baidu.com")
private Resource url; // 注入U(xiǎn)RL資源
2.2.通過配置文件注入屬性的情況
在項(xiàng)目的src/main/resources目錄下新建一個(gè)屬性文件,例如person.properties,其內(nèi)容如下:
person.nickName=liqb
新建MainConfigOfPropertyValues配置類,在該類上使用@PropertySource注解讀取外部配置文件中的key/value并保存到運(yùn)行的環(huán)境變量中
package com.tianxia.springannotation.config;
import com.tianxia.springannotation.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 配置類
* @author liqb
* @date 2023-05-04 11:28
**/
@Configuration
@PropertySource(value={"classpath:/person.properties"})
public class MainConfigOfPropertyValues {
@Bean
public Person person() {
return new Person();
}
}
加載完外部的配置文件以后,就可以使用${key}取出配置文件中key所對(duì)應(yīng)的值,并將其注入到bean的屬性中了
package com.tianxia.springannotation.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import java.io.Serializable;
/**
* Person類
* @author liqb
* @date 2023-04-21 16:00
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private Integer age;
/**
* 昵稱
*/
@Value("${person.nickName}")
private String nickName;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
2.3.@Value中#{···}和${···}的區(qū)別
提供一個(gè)測(cè)試屬性文件,advance_value_inject.properties,內(nèi)容如下所示
server.name=server1,server2,server3 author.name=liqb
新建AdvanceValueInject類,并在該類上使用@PropertySource注解讀取外部屬性文件中的key/value并保存到運(yùn)行的環(huán)境變量中,即加載外部的advance_value_inject.properties屬性文件。
package com.tianxia.springannotation.config;
import com.tianxia.springannotation.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 配置類
* @author liqb
* @date 2023-05-04 11:28
**/
@Configuration
@PropertySource(value={"classpath:/person.properties"})
public class MainConfigOfPropertyValues {
@Bean
public Person person() {
return new Person();
}
}
2.3.1.${···}的用法
{}里面的內(nèi)容必須符合SpEL表達(dá)式,通過@Value(“${spelDefault.value}”)我們可以獲取屬性文件中對(duì)應(yīng)的值,但是如果屬性文件中沒有這個(gè)屬性,那么就會(huì)報(bào)錯(cuò)。不過,我們可以通過賦予默認(rèn)值來解決這個(gè)問題,如下所示。
@Value("${author.name:liqb}")
private String name;
表示向bean的屬性中注入屬性文件中的author.name屬性所對(duì)應(yīng)的值,如果屬性文件中沒有author.name這個(gè)屬性,那么便向bean的屬性中注入默認(rèn)值liqb。
2.3.2.#{···}的用法
{}里面的內(nèi)容同樣也是必須符合SpEL表達(dá)式。例如,
// SpEL:調(diào)用字符串Hello World的concat方法
@Value("#{'Hello World'.concat('!')}")
private String helloWorld;
// SpEL:調(diào)用字符串的getBytes方法,然后再調(diào)用其length屬性
@Value("#{'Hello World'.bytes.length}")
private String helloWorldBytes;
2.3.3.${···}和#{···}的混合使用
${···}和#{···}可以混合使用,例如:
// SpEL:傳入一個(gè)字符串,根據(jù)","切分后插入列表中, #{}和${}配合使用時(shí),注意不能反過來${}在外面,而#{}在里面
@Value("#{'${server.name}'.split(',')}")
private List<String> severs;
上面片段的代碼的執(zhí)行順序:通過**${server.name}從屬性文件中獲取值并進(jìn)行替換,然后就變成了執(zhí)行SpEL表達(dá)式{‘server1,server2,server3’.split(‘,’)}**。
2.3.4.小結(jié)
#{···}:用于執(zhí)行SpEl表達(dá)式,并將內(nèi)容賦值給屬性
${···}:主要用于加載外部屬性文件中的值
${···}和#{···}可以混合使用,但是必須#{}在外面
以上就是利用@Value注解為bean的屬性賦值方法總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于@Value為bean屬性賦值的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring中OpenFeign的使用方法最佳實(shí)踐
這篇文章主要介紹了Spring中OpenFeign使用的相關(guān)資料,OpenFeign是一個(gè)聲明式的WebService客戶端,簡(jiǎn)化了微服務(wù)之間的調(diào)用,類似于Controller調(diào)用Service,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-02-02
JAVA使用DBUtils操作數(shù)據(jù)庫(kù)
這篇文章主要介紹了JAVA使用DBUtils操作數(shù)據(jù)庫(kù)的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家學(xué)習(xí)JAVA,感興趣的朋友可以了解下2020-07-07
SpringBoot3.x集成nacos并實(shí)現(xiàn)多環(huán)境配置的操作步驟
本文詳細(xì)介紹了如何在Springboot3.x中集成Nacos2.x版本,包括nacos的安裝、配置更改,以及在集成過程中遇到的問題,如端口設(shè)置、依賴版本調(diào)整等,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10
Springboot3利用redis生成唯一訂單號(hào)的實(shí)現(xiàn)示例
本文主要介紹了Springboot3利用redis生成唯一訂單號(hào)的實(shí)現(xiàn)示例,包括UUID、雪花算法和數(shù)據(jù)庫(kù)約束,具有一定的參考價(jià)值,感興趣的可以了解一下2025-03-03
Java垃圾回收機(jī)制的finalize方法實(shí)例分析
這篇文章主要介紹了Java垃圾回收機(jī)制的finalize方法,結(jié)合實(shí)例形式分析了finalize方法的特點(diǎn)及在垃圾回收機(jī)制中的相關(guān)操作技巧,需要的朋友可以參考下2019-08-08
微服務(wù)?Spring?Boot?整合?Redis?BitMap?實(shí)現(xiàn)?簽到與統(tǒng)計(jì)功能
這篇文章主要介紹了微服務(wù)?Spring?Boot?整合?Redis?BitMap?實(shí)現(xiàn)?簽到與統(tǒng)計(jì)功能,文章簡(jiǎn)單介紹了Redis BitMap 基本用法結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01
SpringBoot3實(shí)現(xiàn)上傳圖片并返回路徑讓前端顯示圖片
這篇文章主要介紹了SpringBoot3實(shí)現(xiàn)上傳圖片并返回路徑讓前端顯示圖片,文中通過圖文和代碼講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-12-12
淺談xml配置spring profiles的幾個(gè)注意點(diǎn)
這篇文章主要介紹了淺談xml配置spring profiles的幾個(gè)注意點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07

