关于@Value取值为NULL的解决方案
@Value取值为NULL的问题
在spring mvc架构中,如果希望在程序中直接使用properties中定义的配置值,通常使用一下方式来获取:
@Value("${tag}")
private String tagValue;但是取值时,有时这个tagvalue为NULL,可能原因有:
使用static或final修饰了tagValue,如下:
private static String tagValue; //错误 private final String tagValue; //错误
类没有加上@Component(或者@service等)
@Component //遗漏
class TestValue{
@Value("${tag}")
private String tagValue;
}类被new新建了实例,而没有使用@Autowired
@Component
class TestValue{
@Value("${tag}")
private String tagValue;
}
class Test{
...
TestValue testValue = new TestValue()
}这个testValue中肯定是取不到值的,必须使用@Autowired:
class Test{
@AutoWired
TestValue testValue
}@Value取值为NULL原因分析
有两种方式:
@Value(“${}”)用于获取配置文件中的属性值,通常用于获取写在application.properties中的内容;@Value(“#{}”)其实是SpEL表达式的值,可以表示常量的值,或者获取bean中的属性
区别:
① ${ property : default_value }//property对应外部配置文件,default_value,就是前面的值为空时的默认值。② #{ obj.property? :default_value }//SpEL表达式,obj代表对象
一.@Value(“${}”)的使用
@Value("${inputDir}")
private String inputDir;但有时候@Value(“${}”)取值为NULL,可能是由下面几个原因造成的:
1.类没有交给spring管理,即没有加上@Component等注解
@Service
public class TestValue{
@Value("${inputDir}")
private String inputDir;
……
}
2.使用 static或final修饰成员变量
@Value("${inputDir}")
private static String inputDir;//错误,不能使用@Value给static成员变量赋值
@Value("${inputDir}")
private final String inputDir;//错误,不能使用@Value给final成员变量赋值3.自己new了一个对象实例,而没有使用@Autowired注解
class Test{
@AutoWired
TestValue testValue
//TestValue testValue = new TestValue()//错误,自己new的对象不能通过@Value注解获取配置值。
}二.@Value{“#{}”}的使用
@RestController
@RequestMapping("/login")
@Component
public class LoginController {
@Value("#{1}")
private int number; //获取数字 1
@Value("#{'Spring Expression Language'}") //获取字符串常量
private String str;
@Value("#{dataSource.url}") //获取bean的属性,dataSource为spring管理的obj,不是配置文件中的配置项
private String jdbcUrl;
@Autowired
private DataSourceTransactionManager transactionManager;
@RequestMapping("login")
public String login(String name,String password) throws FileNotFoundException{
System.out.println(number);
System.out.println(str);
System.out.println(jdbcUrl);
return "login";
}
}运行结果

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
java如何从地址串中解析提取省市区(完美匹配中国所有地址)
这篇文章主要给大家介绍了关于java如何从地址串中解析提取省市区的相关资料,通过这个方法可以完美匹配中国所有地址,文中通过示例代码介绍的非常详细,需要的朋友可以参考下2022-07-07
Spring 源码解析CommonAnnotationBeanPostProcessor
这篇文章主要为大家介绍了Spring 源码解析CommonAnnotationBeanPostProcessor示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10
Spring Boot Actuator监控器配置及使用解析
这篇文章主要介绍了Spring Boot Actuator监控器配置及使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-07-07


最新评论