mTv*_*mTv 4 java spring spring-boot
我正在尝试使用服务实现类/ bean中的application.properties文件中的值。但是,当通过我的config类初始化bean时,属性值全部为null。
配置类:
@Configuration
public class AppConfig {
@Bean AppServiceImpl appServiceImpl() {
return new AppServiceImpl();
}
}
Run Code Online (Sandbox Code Playgroud)
服务等级:
@Component
public class AppServiceImpl implements AppService {
@Value("${value.one}")
String value_one;
@Value("${value.two}")
String value_two;
@Value("${value.three}")
String value_three;
//values are null here
public AppServiceImpl() {
functionOne(value_one, value_two, value_three);
}
}
Run Code Online (Sandbox Code Playgroud)
application.properties(在src / main / resources下):
value.one=1
value.two=2
value.three=3
Run Code Online (Sandbox Code Playgroud)
做一些调试,我可以看到AppConfig类已经找到了属性文件,如果我尝试声明该属性文件,则@Value("${value.one}") String value_one;表明它已得到1预期的值。
但是在我的AppServiceImpl类中,所有值都是null。我在这里做错了什么?如何在Springboot中正确完成此操作?甚至只是春天。
谢谢。
如果您在构造函数中使用这些值,则将无法立即使用它们。实际上,它们是基于属性注入的。这里发生的事情是在spring创建实例之后,它将更新属性值。
如果要在构造函数中使用这些值,则应使用构造函数注入。构造函数的注入是最佳实践。
public class AppServiceImpl implements AppService {
String value_one;
String value_two;
String value_three;
//values are null here
public AppServiceImpl(String value1, String value2, String value3) {
value_one = value1;
value_two = value2;
value_three = value3;
functionOne(value_one, value_two, value_three);
}
}
Run Code Online (Sandbox Code Playgroud)
还有你的配置类
@Configuration
public class AppConfig {
@Bean AppServiceImpl appServiceImpl(@Value("${value.one}") String value1, @Value("${value.two}") String value2, @Value("${value.three}") String value3) {
return new AppServiceImpl(value1, value2, value3);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2184 次 |
| 最近记录: |