基于Spring boot @Value 注解注入属性值的操作方法

网友投稿 333 2022-12-01


基于Spring boot @Value 注解注入属性值的操作方法

本文主要介绍Spring @Value 注解注入属性值的使用方法的分析,文章通过示例代码非常详细地介绍,对于每个人的学习或工作都有一定的参考学习价值

在使用spring框架的项目中,@Value是经常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在日常使用中,我们常用的功能相对简单。本文使您系统地了解@Value的用法。

@Value注入形式

根据注入的内容来源,@ Value属性注入功能可以分为两种:通过配置文件进行属性注入和通过非配置文件进行属性注入。

非配置文件注入的类型如下:

注入普通字符串注入操作系统属性注射表达结果注入其他bean属性注入文件资源注入URL资源

基于配置文件的注入

首先,让我们看一下配置文件中的数据注入,无论它是默认加载的application.properties还http://是自定义my.properties文档(需要@PropertySource额外加载)。例如:application.properties属性值以以下形式定义:

user.name=admin

my.properties配置文件中定义的属性如下:

user.password=pwd123

然后,在bean中使用@Value,如下所示:

@PropertySource("classpRaLgGath: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 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 numList;

/**

*注入一个文件资源

*/

@Value("classpath:config.xml")

private Resouhttp://rce resourceFile;

/**

*注入 URL 资源

*/

@Value("http://choupangxia.com")

private URL homePage;

上面的示例显示了以下方案的使用:

直接注入字符串等效于实例化时直接初始化字符串。初始化空串

通过#{}注入系统变量。

表达式计算结果通过#{}注入。

通过#{}注入其他bean的属性。

通过{}和$ {}的组合注入属性,然后拆分。

注入文件资源,并将相应的字符串值转换为相应的资源文件。

注入URL资源并将相应的URL字符串转换为URL

默认值注入

无论使用#{}(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;

$ {}中直接使用“:”来设置未定义或空值的默认值,而#{}则需要使用“?:”来设置未设置属性的默认值。

总结


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:JAVA模拟新增顺序表及单链表
下一篇:SpringBoot如何优雅地使用Swagger2
相关文章

 发表评论

暂时没有评论,来抢沙发吧~