@Value取值为NULL怎么办,解决方案有哪些
导读:相信很多人对“@Value取值为NULL怎么办,解决方案有哪些”都不太了解,下文有实例供大家参考,对大家了解操作过程或相关知识有一定的帮助,而且内容详细,逻辑清晰,接下来小编就为你详细解释一下这个问题。 @Value取值为NULL的问题...
相信很多人对“@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";
}
}
运行结果
到此这篇关于“@Value取值为NULL怎么办,解决方案有哪些”的文章就介绍到这了,感谢各位的阅读,更多相关@Value取值为NULL怎么办,解决方案有哪些内容,欢迎关注网络资讯频道,小编将为大家输出更多高质量的实用文章!
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: @Value取值为NULL怎么办,解决方案有哪些
本文地址: https://pptw.com/jishu/652224.html
