SpringBoot屬性注入的兩種方法
1、實(shí)現(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}
注意:此方法是不安全的,如果在配置文件中找不到對應(yīng)的屬性,例如沒有username屬性,會報(bào)錯(cuò)如下:
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、實(shí)現(xiàn)方式二:通過SpringBoot特有的@ConfigurationProperties來實(shí)現(xiàn)
注意點(diǎ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屬性注入的兩種方法的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot屬性注入的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Ajax提交post請求案例分析2. python 批量下載bilibili視頻的gui程序3. 使用css實(shí)現(xiàn)全兼容tooltip提示框4. python numpy庫np.percentile用法說明5. 一篇文章弄清楚Ajax請求的五個(gè)步驟6. PHP 面向?qū)ο蟪绦蛟O(shè)計(jì)之類屬性與類常量實(shí)現(xiàn)方法分析7. python中HTMLParser模塊知識點(diǎn)總結(jié)8. Java Spring WEB應(yīng)用實(shí)例化如何實(shí)現(xiàn)9. CSS自定義滾動(dòng)條樣式案例詳解10. JSP實(shí)現(xiàn)客戶信息管理系統(tǒng)
