SpringBoot项目中通过@Value给参数赋值失败的解决方案
更新时间:2024年04月29日 09:31:28 作者:Keep Doing this
springboot项目中通过@Value给属性附值失败,给参数赋值失败,打印为空值,文中通过代码示例给大家介绍的非常详细,对大家解决问题有一定的帮助,需要的朋友可以参考下
项目场景:
springboot项目中通过@Value给属性附值失败
问题描述
给参数赋值失败,打印为空值
@Value("${python.server.port}")
private int port;
@Value("${python.server.host}")
private String host;
public PythonSocketClient(){
System.out.println("Host: " + host);
System.out.println("Port: " + port);
connect();
}
测试发现是成功注入的
@SpringBootTest
public class ValueTest {
@Value("${python.server.host}")
private String host;
@Test
public void testConfiguration() {
System.out.println("Host configured as: " + host);
}
}可以看到是正确赋值了

原因分析:
这是因为在 Spring Bean 的生命周期中,构造函数是最先被调用的,此时依赖注入还没有完成,因此 @Value 注入的字段尚未被初始化。
也就是说还没附上值就运行了构造器
解决方案:
使用 @PostConstruct 注解的方法来确保在所有字段注入完成之后再执行初始化逻辑。
@Value("${python.server.port}")
private int port;
@Value("${python.server.host}")
private String host;
@PostConstruct
public void init() {
System.out.println("Host: " + host);
System.out.println("Port: " + port);
connect();
}再次运行

发现已经可以正常获取值了。
到此这篇关于SpringBoot项目中通过@Value给参数赋值失败的解决方案的文章就介绍到这了,更多相关SpringBoot @Value赋值失败内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
完美解决java.lang.OutOfMemoryError处理错误的问题
下面小编就为大家带来一篇完美解决java.lang.OutOfMemoryError处理错误的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-01-01


最新评论