SpringBoot屬性注入的兩種方法
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}
注意:此方法是不安全的,如果在配置文件中找不到對應(yīng)的屬性,例如沒有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)容,更多關(guān)于SpringBoot屬性注入的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Nginx+php配置文件及原理解析2. Intellij IDEA 2019 最新亂碼問題及解決必殺技(必看篇)3. Android自定義View實現(xiàn)掃描效果4. java中throws實例用法詳解5. Opencv+Python識別PCB板圖片的步驟6. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效7. IOS利用CocoaHttpServer搭建手機本地服務(wù)器8. Android Manifest中meta-data擴展元素數(shù)據(jù)的配置與獲取方式9. css3溢出隱藏的方法10. ASP.NET MVC獲取多級類別組合下的產(chǎn)品
