Python 官方文档:入门教程 => 点击学习
目录@Value获取application.properties配置无效问题@Value获取application.properties中的配置取值为Null解决方法正确做法总结@V
无效的原因主要是要注意@Value使用的注意事项:
这些注意事项也是由它的原理决定的:
SpringBoot启动过程中,有两个比较重要的过程,如下:
@Value的解析就是在第二个阶段。BeanPostProcessor定义了bean初始化前后用户可以对bean进行操作的接口方法,它的一个重要实现类AutowiredAnnotationBeanPostProcessor正如javadoc所说的那样,为bean中的@Autowired和@Value注解的注入功能提供支持。
下面说下两种方式:
resource.test.imageServer=Http://image.everest.com
1、第一种
@Configuration
public class EverestConfig {
@Value("${resource.test.imageServer}")
private String imageServer;
public String getImageServer() {
return imageServer;
}
}
2、第二种
@Component
@ConfigurationProperties(prefix = "resource.test")
public class TestUtil {
public String imageServer;
public String getImageServer() {
return imageServer;
}
public void setImageServer(String imageServer) {
this.imageServer = imageServer;
}
}
然后在需要的地方注入就可
@Autowired
private TestUtil testUtil;
@Autowired
private EverestConfig everestConfig;
@GetMapping("getImageServer")
public String getImageServer() {
return testUtil.getImageServer();
// return everestConfig.getImageServer();
}
@Value("${spring.datasource.url}")
private String url;
获取值为NUll。
不要使用new的方法去创建工具类(DBUtils)对象,而是使用@Autowired的方式交由springboot来管理,在工具类上加上@Component,定义的属性变量不要加static。
@Autowired
private DBUtils jdbc;
@Component
public class DBUtils{
@Value("${spring.datasource.url}")
private String url;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: SpringBoot之@Value获取application.properties配置无效的解决
本文链接: https://www.lsjlt.com/news/198727.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0