国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

SpringBoot屬性注入的兩種方法

瀏覽:83日期:2023-04-10 10:48:42

1、實現(xiàn)方式一:Spring中的@PropertySource

@Component@PropertySource('classpath:user.properties')public class UserInfo { @Value('${user.username}') private String username; @Value('${user.password}') private String password; @Value('${user.age}') private Integer age; @Override public String toString() { return 'UserInfo{' + 'username=’' + username + ’’’ + ', password=’' + password + ’’’ + ', age=' + age + ’}’; }}

配置文件中:

user.username=’admin’user.password=’123’user.age=88

測試:

@SpringBootTestpublic class UserInfoTest { @Autowired UserInfo userInfo; @Test public void user(){ System.out.println(userInfo.toString()); }}

結(jié)果:

UserInfo{username=’’admin’’, password=’’123’’, age=88}

注意:此方法是不安全的,如果在配置文件中找不到對應的屬性,例如沒有username屬性,會報錯如下:

java.lang.IllegalStateException: Failed to load ApplicationContextCaused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ’userInfo’: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ’user.username’ in value '${user.username}'

2、實現(xiàn)方式二:通過SpringBoot特有的@ConfigurationProperties來實現(xiàn)

注意點: 需要getter、setter函數(shù)

@Component@PropertySource('classpath:user.properties')@ConfigurationProperties(prefix = 'user')public class UserInfo {// @Value('${user.username}') private String username;// @Value('${user.password}') private String password;// @Value('${user.age}') private Integer age; public String getUsername() { return username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return 'UserInfo{' + 'username=’' + username + ’’’ + ', password=’' + password + ’’’ + ', age=' + age + ’}’; }}

這種方法比較安全,即使配置文件中沒有對于屬性,也不會拋出異常。

以上就是SpringBoot屬性注入的兩種方法的詳細內(nèi)容,更多關于SpringBoot屬性注入的資料請關注好吧啦網(wǎng)其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 南丹县| 阿鲁科尔沁旗| 凤山市| 九江县| 华蓥市| 错那县| 曲松县| 龙陵县| 甘德县| 乌审旗| 白城市| 龙游县| 靖边县| 鸡西市| 宣化县| 汕头市| 双流县| 肥东县| 靖州| 沙河市| 隆回县| 轮台县| 娄底市| 扎赉特旗| 曲麻莱县| 满城县| 云梦县| 荥阳市| 正镶白旗| 沁水县| 正镶白旗| 班玛县| 靖远县| 尤溪县| 九江市| 乌鲁木齐市| 大宁县| 漠河县| 合江县| 乌海市| 招远市|