SpringBoot 使用 @Value 注解讀取配置文件給靜態(tài)變量賦值
1、application.properties 配置文件
mail.username=xue@163.commail.password=xuemail.host=smtp.163.commail.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 注解無(wú)效
4、給靜態(tài)變量賦值
1、使用 set 方法
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic 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;@Componentpublic 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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 解決ajax請(qǐng)求后臺(tái),有時(shí)收不到返回值的問(wèn)題2. ASP.NET MVC通過(guò)勾選checkbox更改select的內(nèi)容3. ASP中實(shí)現(xiàn)字符部位類似.NET里String對(duì)象的PadLeft和PadRight函數(shù)4. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考5. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)6. asp知識(shí)整理筆記4(問(wèn)答模式)7. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼8. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟9. jsp+mysql實(shí)現(xiàn)網(wǎng)頁(yè)的分頁(yè)查詢10. ASP基礎(chǔ)知識(shí)Command對(duì)象講解
