@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注解的注入功能提供支持。
下面说下两种方式:
resource.test.imageserver=http://image.everest.com
1、第一种
@configurationpublic 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获取application.properties中的配置取值为null@value("${spring.datasource.url}")private string url;
获取值为null。
解决方法不要使用new的方法去创建工具类(dbutils)对象,而是使用@autowired的方式交由springboot来管理,在工具类上加上@component,定义的属性变量不要加static。
正确做法@autowiredprivate dbutils jdbc; @componentpublic class dbutils{ @value("${spring.datasource.url}") private string url;}
以上就是springboot之@value获取application.properties配置无效如何解决的详细内容。