本文主要介绍Spring @Value 注解注入属性值的使用方法的分析,文章经过示例代码很是详细地介绍,对于每一个人的学习或工做都有必定的参考学习价值vue
在使用spring框架的项目中,@Value是常常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在平常使用中,咱们经常使用的功能相对简单。本文使您系统地了解@Value的用法。java
根据注入的内容来源,@ Value属性注入功能能够分为两种:经过配置文件进行属性注入和经过非配置文件进行属性注入。spring
非配置文件注入的类型以下:后端
首先,让咱们看一下配置文件中的数据注入,不管它是默认加载的application.properties仍是自定义my.properties文档(须要@PropertySource额外加载)。例如:application.properties属性值以如下形式定义:数组
user.name=admin
my.properties配置文件中定义的属性以下:springboot
user.password=pwd123
而后,在bean中使用@Value,以下所示:app
@PropertySource("classpath:my.properties") @RestController public class ValueController { /** *Get in application.properties Properties configured in */ @Value("${user.name}") private String name; /** *Get in my.properties Configuration properties in */ @Value("${user.password}") private String password; }
区别在于,在spring boot项目中,若是使用my.properties文件,则须要经过类中的@ PropertySource导入配置文件,而application.properties中的属性将自动加载。框架
同时,您不只能够经过@Value注入单个属性,还能够采用数组和列表的形式。例如,配置以下:前后端分离
tools=car,train,airplane
能够经过如下方式注入它:dom
/** *Injection array (automatically split according to ",") */ @Value("${tools}") private String[] toolArray; /** *Injection list form (automatic segmentation based on "," and) */ @Value("${tools}") private List<String> toolList;
默认状况下,spring将以“,”分割,并将其转换为相应的数组或列表。
在使用示例说明基于非配置文件注入属性的实例以前,让咱们看一下SpEl。
Spring Expression Language是Spring表达式语言,能够在运行时查询和操做数据。使用#{…}做为操做符号,大括号中的全部字符均视为SpEl。
让咱们看一下特定实例场景的应用:
/** *实例化一个字符串,并赋予默认值 */ @Value private String wechatSubscription; /** *读取系统的环境变量 */ @Value("#{systemProperties['os.name']}") private String systemPropertiesName; /** *注入表达式计算结果 */ @Value("#{ T(java.lang.Math).random() * 100.0 }") private double randomNumber; /** *读取一个bean:config的tool属性并注入 */ @Value("#{config.tool}") private String tool; /** *将words用“|”分隔为字符串数组 */ @Value("#{'${words}'.split('\|')}") private List<String> numList; /** *注入一个文件资源 */ @Value("classpath:config.xml") private Resource resourceFile; /** *注入 URL 资源 */ @Value("http://www.choupangxia.com") private URL homePage;
上面的示例显示了如下方案的使用:
不管使用#{}(SpEL)仍是$ {}进行属性注入,当没法得到相应的值时,都须要设置默认值,能够经过如下方式进行设置。
/** *If IP is not configured in the property, the default value is used */ @Value("${ip:127.0.0.1}") private String ip; /** *If the value of port is not obtained in the system properties, 8888 is used. */ @Value("#{systemProperties['port']?:'8888'}") private String port;
$ {}中直接使用“:”来设置未定义或空值的默认值,而#{}则须要使用“?:”来设置未设置属性的默认值。
以为对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创做动力! 。另外,笔者最近一段时间输出了以下的精品内容,期待您的关注。