SpringBoot 使用 @Value 注解讀取配置文件給靜態(tài)變量賦值
1、application.properties 配置文件
mail.username=xue@163.com mail.password=xue mail.host=smtp.163.com mail.smtp.auth=true
2、給普通變量賦值,直接在變量上添加 @Value 注解
import org.springframework.beans.factory.annotation.Value;
public class MailConfig {
@Value("${mail.username}")
private String username;
@Value("${mail.password}")
private String password;
@Value("${mail.host}")
private String host;
}
3、給靜態(tài)變量賦值,直接在靜態(tài)變量上添加 @Value 注解無效

4、給靜態(tài)變量賦值
1、使用 set 方法
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MailConfig {
public static String username;
public static String password;
public static String host;
@Value("${mail.username}")
public void setUsername(String username) {
this.username = username;
}
@Value("${mail.password}")
public void setPassword(String password) {
this.password = password;
}
@Value("${mail.host}")
public void setHost(String host) {
this.host = host;
}
}
2、使用 @PostConstruct(推薦使用)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class MailConfig {
public static String USERNAME;
public static String PASSWORD;
public static String HOST;
@Value("${mail.username}")
private String username;
@Value("${mail.password}")
private String password;
@Value("${mail.host}")
private String host;
@PostConstruct
public void init() {
USERNAME = username;
PASSWORD = password;
HOST = host;
}
}
到此這篇關(guān)于SpringBoot 使用 @Value 注解讀取配置文件給靜態(tài)變量賦值的文章就介紹到這了,更多相關(guān)SpringBoot @Value 靜態(tài)變量賦值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot讀取application.yml報(bào)錯問題及解決
這篇文章主要介紹了springboot讀取application.yml報(bào)錯問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringMVC Json自定義序列化和反序列化的操作方法
這篇文章主要介紹了SpringMVC Json自定義序列化和反序列化的操作方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
基于Spring Batch向Elasticsearch批量導(dǎo)入數(shù)據(jù)示例
本文介紹了基于Spring Batch向Elasticsearch批量導(dǎo)入數(shù)據(jù)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
springcloud本地調(diào)試feign調(diào)用出現(xiàn)的詭異404問題及解決
Springboot通過url訪問本地圖片代碼實(shí)例
Java基于socket實(shí)現(xiàn)簡易聊天室實(shí)例

