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. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)2. css代碼優(yōu)化的12個技巧3. CSS可以做的幾個令你嘆為觀止的實例分享4. xml中的空格之完全解說5. ASP刪除img標簽的style屬性只保留src的正則函數(shù)6. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法7. 利用ajax+php實現(xiàn)商品價格計算8. Vue的Options用法說明9. axios和ajax的區(qū)別點總結(jié)10. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?
