这篇文章将为大家详细讲解有关如何在Spring boot实现@Value注解注入属性值,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
本文主要介绍Spring @Value 注解注入属性值的使用方法的分析,文章通过示例代码非常详细地介绍,对于每个人的学习或工作都有一定的参考学习价值
在使用spring框架的项目中,@Value是经常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在日常使用中,我们常用的功能相对简单。本文使您系统地了解@Value的用法。
@Value注入形式
基于配置文件的注入
首先,让我们看一下配置文件中的数据注入,无论它是默认加载的application.properties还是自定义my.properties文档(需要@PropertySource额外加载)。例如:application.properties属性值以以下形式定义:
user.name=admin
my.properties配置文件中定义的属性如下:
user.password=pwd123
然后,在bean中使用@Value,如下所示:
@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
可以通过以下方式注入它:
/**
*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;
$ {}中直接使用“:”来设置未定义或空值的默认值,而#{}则需要使用“?:”来设置未设置属性的默认值。
关于如何在Spring boot实现@Value注解注入属性值就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。