SpringBoot屬性注入的兩種方法
阿新 • • 發佈:2020-11-11
1、實現方式一: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
測試:
@SpringBootTest public class UserInfoTest { @Autowired UserInfo userInfo; @Test public void user(){ System.out.println(userInfo.toString()); } }
結果:
UserInfo{username=''admin'',password=''123'',age=88}
注意:此方法是不安全的,如果在配置檔案中找不到對應的屬性,例如沒有username屬性,會報錯如下:
java.lang.IllegalStateException: Failed to load ApplicationContext Caused 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、實現方式二:通過SpringBoot特有的@ConfigurationProperties來實現
注意點: 需要getter、setter函式
@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 + '\'' + ",age=" + age + '}'; } }
這種方法比較安全,即使配置檔案中沒有對於屬性,也不會丟擲異常。
以上就是SpringBoot屬性注入的兩種方法的詳細內容,更多關於SpringBoot屬性注入的資料請關注我們其它相關文章!