这篇文章主要讲解了“@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(“${}”)
用于获取配置文件中的属性值,通常用于获取写在application.properties中的内容;
@Value(“#{}”)
其实是SpEL表达式的值,可以表示常量的值,或者获取bean中的属性
区别:
① ${ property : default_value }
//property对应外部配置文件,default_value,就是前面的值为空时的默认值。
② #{ obj.property? :default_value }
//SpEL表达式,obj代表对象
@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注解获取配置值。
}
@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怎么解决这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。