经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot之@Value获取application.properties配置无效的解决
来源:jb51  时间:2023/3/8 10:58:56  对本文有异议

@Value获取application.properties配置无效问题

无效的原因主要是要注意@Value使用的注意事项:

  • 1、不能作用于静态变量(static);
  • 2、不能作用于常量(final);
  • 3、不能在非注册的类中使用(需使用@Componet、@Configuration等);
  • 4、使用有这个属性的类时,只能通过@Autowired的方式,用new的方式是不会自动注入这些配置的。

这些注意事项也是由它的原理决定的:

springboot启动过程中,有两个比较重要的过程,如下:

  • 1 、扫描,解析容器中的bean注册到beanFactory上去,就像是信息登记一样。
  • 2、 实例化、初始化这些扫描到的bean。

@Value的解析就是在第二个阶段。BeanPostProcessor定义了bean初始化前后用户可以对bean进行操作的接口方法,它的一个重要实现类AutowiredAnnotationBeanPostProcessor正如javadoc所说的那样,为bean中的@Autowired和@Value注解的注入功能提供支持。

下面说下两种方式:

  1. resource.test.imageServer=http://image.everest.com

1、第一种

  1. @Configuration
  2. public class EverestConfig {
  3. ?
  4. ? ? @Value("${resource.test.imageServer}")
  5. ? ? private String imageServer;
  6. ?
  7. ? ? public String getImageServer() {
  8. ? ? ? ? return imageServer;
  9. ? ? }
  10. ?
  11. }

2、第二种

  1. @Component
  2. @ConfigurationProperties(prefix = "resource.test")
  3. public class TestUtil {
  4. ?
  5. ? ? public String imageServer;
  6. ?
  7. ? ? public String getImageServer() {
  8. ? ? ? ? return imageServer;
  9. ? ? }
  10. ?
  11. ? ? public void setImageServer(String imageServer) {
  12. ? ? ? ? this.imageServer = imageServer;
  13. ? ? }
  14. }

然后在需要的地方注入就可

  1. ? ? @Autowired
  2. ? ? private TestUtil testUtil;
  3. ?
  4. ? ? @Autowired
  5. ? ? private EverestConfig everestConfig;
  6. ?
  7. ?
  8. ? ? @GetMapping("getImageServer")
  9. ? ? public String getImageServer() {
  10. ? ? ? ? return testUtil.getImageServer();
  11. // ? ? ? ?return everestConfig.getImageServer();
  12. ? ? }?

@Value获取application.properties中的配置取值为Null

  1. @Value("${spring.datasource.url}")
  2.  
  3. private String url;

获取值为NUll。

解决方法

不要使用new的方法去创建工具类(DBUtils)对象,而是使用@Autowired的方式交由springboot来管理,在工具类上加上@Component,定义的属性变量不要加static。

正确做法

  1. @Autowired
  2. private DBUtils jdbc;
  3. ??
  4. @Component
  5. public class DBUtils{
  6. ? ??
  7. ? ? @Value("${spring.datasource.url}")
  8. ? ? private String url;
  9. }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号