spring@value注入配置文件值失败的原因
今天我写了一个system.propertities配置文件定义了一个变量host=localhost。
然后在spring 配置文件中加入了加载配置
在service中这样写
- @Value("${host}")
- private static String host;
但是获取不到,各种查资料,最后发现是static关键字的原因
spring@Value依赖注入是依赖set方法
set方法是普通的对象方法,static变量是类的属性,没有set方法;
spring配置文件@Value注解注入失败或为null
在spring使用@Value从application.properties将值注入到变量中时,遇到
了注入失败和注入值为null两种问题。
解决方案
1、查看maven依赖,
(如果生效,可不进行后续步骤)
2、加入注释@PropertySource(value = “classpath:/application.properties”)配置文件路径。
(如果生效,可不进行后续步骤)
3、将被注入变量作为构造方法参数进行输入。
代码示例
maven依赖
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>5.1.5.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- <version>2.1.3.RELEASE</version>
- </dependency>
config类
- @Configuration
- //声明properties文件位置
- @PropertySource(value = "classpath:/application.properties")
- public class DemoConfig {
- private String name;
- //将@Value作为构造函数参数注入
- public DemoConfig(@Value("${book.name}") String name){
- this.name = name;
- }
- public void output(){
- System.out.println(name);
- }
- }
main
- @SpringBootApplication
- public class DemoApplication {
- public static void main(String[] args) {
- // SpringApplication.run(DemoApplication.class, args);
- AnnotationConfigApplicationContext context =
- new AnnotationConfigApplicationContext(DemoConfig.class);
- DemoConfig service = context.getBean(DemoConfig.class);
- service.output();
- }
- }
问题解析
1、spring版本问题,根据本人实验,4.x以下版本会出现一些注入问题。
2、没有写@PropertySource(value = “classpath:/application.properties”)注解,或路径不对。
3、.properties文件没有放在resources文件夹中。
问题拓展
1、除了springboot自带的application.properties文件外,可以自己创建test.properties,导入其他自创属性,并管理属性。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。