SpringBoot属性注入的两种方法
1、实现方式一:Spring中的@PropertySource
@Component
@PropertySource("classpath:user.properties")
publicclassUserInfo{
@Value("${user.username}")
privateStringusername;
@Value("${user.password}")
privateStringpassword;
@Value("${user.age}")
privateIntegerage;
@Override
publicStringtoString(){
return"UserInfo{"+
"username='"+username+'\''+
",password='"+password+'\''+
",age="+age+
'}';
}
}
配置文件中:
user.username='admin' user.password='123' user.age=88
测试:
@SpringBootTest
publicclassUserInfoTest{
@Autowired
UserInfouserInfo;
@Test
publicvoiduser(){
System.out.println(userInfo.toString());
}
}
结果:
UserInfo{username=''admin'',password=''123'',age=88}
注意:此方法是不安全的,如果在配置文件中找不到对应的属性,例如没有username属性,会报错如下:
java.lang.IllegalStateException:FailedtoloadApplicationContext
Causedby:org.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname'userInfo':Injectionofautowireddependenciesfailed;nestedexceptionisjava.lang.IllegalArgumentException:Couldnotresolveplaceholder'user.username'invalue"${user.username}"
2、实现方式二:通过SpringBoot特有的@ConfigurationProperties来实现
注意点:需要getter、setter函数
@Component
@PropertySource("classpath:user.properties")
@ConfigurationProperties(prefix="user")
publicclassUserInfo{
//@Value("${user.username}")
privateStringusername;
//@Value("${user.password}")
privateStringpassword;
//@Value("${user.age}")
privateIntegerage;
publicStringgetUsername(){
returnusername;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicIntegergetAge(){
returnage;
}
publicvoidsetAge(Integerage){
this.age=age;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
@Override
publicStringtoString(){
return"UserInfo{"+
"username='"+username+'\''+
",password='"+password+'\''+
",age="+age+
'}';
}
}
这种方法比较安全,即使配置文件中没有对于属性,也不会抛出异常。
以上就是SpringBoot属性注入的两种方法的详细内容,更多关于SpringBoot属性注入的资料请关注毛票票其它相关文章!