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

編輯RedisController
@RestController
//動態(tài)導(dǎo)入pro配置文件,交給spring容器進行加載
@PropertySource("classpath:/properties/redis.properties")
public class RedisController {
//通過YML給屬性賦值
@Value("${redis.host}")//sple表達式
private String host;
@Value("${redis.port}")
private Integer port;
@RequestMapping("/getMsg")
public String getMsg(){
return host+":"+port;
}
/*由于YML配置文件中的數(shù)據(jù)一般都是系統(tǒng)級別的數(shù)據(jù),所以一般的業(yè)務(wù)數(shù)據(jù)
都會寫到peoperties配置文件中*/
//通過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中屬性賦值操作的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot 屬性賦值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法
這篇文章主要介紹了java實現(xiàn)新浪微博Oauth接口發(fā)送圖片和文字的方法,涉及java調(diào)用新浪微博Oauth接口的使用技巧,具有一定參考接借鑒價值,需要的朋友可以參考下2015-07-07

