SpringBoot中屬性賦值操作的實(shí)現(xiàn)
說(shuō)明:當(dāng)程序中出現(xiàn)頻繁變化的數(shù)據(jù)時(shí),如果采用認(rèn)為的方式進(jìn)行修改并且編譯打包則會(huì)導(dǎo)致代碼的耦合性較高,不便于維護(hù)!所以能否為屬性動(dòng)態(tài)賦值?
屬性固定值
//動(dòng)態(tài)獲取ip和端口數(shù)據(jù)/** * @responseBody * 注解作用: * 1.將對(duì)象轉(zhuǎn)化成Json格式, * 2.如果返回值是String類型,則返回字符串本身 * 3.一般客戶端發(fā)起ajax請(qǐng)求時(shí),采用該注解返回?cái)?shù)據(jù),將不會(huì)執(zhí)行視圖解析器操作 */@RestControllerpublic class RedisController{ private String host='192.168.126.112'; private Integer port=6379; public String getMsg(){ return host+':'+port; }}
動(dòng)態(tài)獲取ip和端口數(shù)據(jù)
關(guān)于YML文件說(shuō)明
#YML文件語(yǔ)法: # 1.key:(空格) value 注意:value前面有個(gè)空格 # 2.key與key之間有層級(jí)的縮進(jìn)關(guān)系server: port: 8090 #屬性賦值操作,編輯屬性時(shí)注意前綴,只要springboot啟動(dòng),該數(shù)據(jù)就會(huì)被寫(xiě)入內(nèi)存中,key-value格式redis: host: 192.168.126.130 port: 6379
為屬性賦值操作
public class RedisController { @Value('${redis.host}') //spel表達(dá)式 private String host; // = '192.168.126.130'; private String host; // = '192.168.126.130'; @Value('${redis.port}') private Integer port; // = 6379; @RequestMapping('/getMsg') public String getMsg(){ return host + ':' + port; }}
指定配置文件為屬性賦值
說(shuō)明:由于YML配置文件中的數(shù)據(jù)一般都是系統(tǒng)級(jí)別的數(shù)據(jù),所以一般的業(yè)務(wù)數(shù)據(jù)都會(huì)寫(xiě)到peoperties配置文件中。

編輯RedisController
@RestController//動(dòng)態(tài)導(dǎo)入pro配置文件,交給spring容器進(jìn)行加載@PropertySource('classpath:/properties/redis.properties')public class RedisController { //通過(guò)YML給屬性賦值 @Value('${redis.host}')//sple表達(dá)式 private String host; @Value('${redis.port}') private Integer port; @RequestMapping('/getMsg') public String getMsg(){ return host+':'+port; } /*由于YML配置文件中的數(shù)據(jù)一般都是系統(tǒng)級(jí)別的數(shù)據(jù),所以一般的業(yè)務(wù)數(shù)據(jù) 都會(huì)寫(xiě)到peoperties配置文件中*/ //通過(guò)properties給屬性賦值 @Value('${pro.redis.host}') private String prohost; @Value('${pro.redis.port}') private Integer proport; @RequestMapping('/getpro') public String getpro(){ return prohost+':'+proport; }}
到此這篇關(guān)于SpringBoot中屬性賦值操作的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot 屬性賦值內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. docker容器調(diào)用yum報(bào)錯(cuò)的解決辦法2. idea環(huán)境下Maven無(wú)法正常下載pom中配置的包問(wèn)題3. 淺談JavaScript宏任務(wù)和微任務(wù)執(zhí)行順序4. vue+elementUI下拉框回顯問(wèn)題及解決方式5. Python Selenium實(shí)現(xiàn)無(wú)可視化界面過(guò)程解析6. Python幾種常見(jiàn)算法匯總7. 使用IntelliJ IDEA 配置安卓(Android)開(kāi)發(fā)環(huán)境的教程詳解(新手必看)8. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟9. 利用Python實(shí)現(xiàn)Excel的文件間的數(shù)據(jù)匹配功能10. Java MultipartFile實(shí)現(xiàn)上傳文件/上傳圖片

網(wǎng)公網(wǎng)安備