springboot中的@vaule注解使用方式
参考网址:
https://mp.weixin.qq.com/s/BG5SDyKN8H1nQhYiotWLkA
说明
在日常开发中,经常会遇到需要在配置文件中,存储 List
或是 Map
这种类型的数据。
Spring 原生是支持这种数据类型的,以配置 List
类型为例,对于 .yml
文件配置如下:
test:
list:
- aaa
- bbb
- ccc
对于 .properties
文件配置如下所示:
test.list[0]=aaa
test.list[1]=bbb
test.list[2]=ccc
当我们想要在程序中使用时候,想当然的使用 @Value
注解去读取这个值,就像下面这种写法一样:
@Value("${test.list}")
private List<String> testList;
你会发现程序直接报错了,报错信息如下:
java.lang.IllegalArgumentException: Could not resolve placeholder 'test.list' in value "${test.list}"
这个问题也是可以解决的,以我们要配置的 key 为 test.list
为例,新建一个 test
的配置类,将 list
作为该配置类的一个属性:
@Configuration
@ConfigurationProperties("test")
public class TestListConfig {
private List<String> list;
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
在程序其他地方使用时候。采用自动注入的方式,去获取值:
@Autowired
private TestListConfig testListConfig;
// testListConfig.getList();
可以看见,这种方式十分的不方便,最大的问题是配置和代码高耦合了,增加一个配置,还需要对配置类做增减改动。
二、数组怎么样
数组?说实话,业务代码写多了,这个“古老”的数据结构远远没有 list 用的多,但是它在解决上面这个问题上,出乎异常的好用。
test:
array1: aaa,bbb,ccc
array2: 111,222,333
array3: 11.1,22.2,33.3
@Value("${test.array1}")
private String[] testArray1;
@Value("${test.array2}")
private int[] testArray2;
@Value("${test.array3}")
private double[] testArray3;
这样就能够直接使用了,就是这么的简单方便,如果你想要支持不配置 key 程序也能正常运行的话,给它们加上默认值即可:
@Value("${test.array1:}")
private String[] testArray1;
@Value("${test.array2:}")
private int[] testArray2;
@Value("${test.array3:}")
private double[] testArray3;
仅仅多了一个 :
号,冒号后的值表示当 key 不存在时候使用的默认值,使用默认值时数组的 length = 0。
总结下使用数组实现的优缺点:
优点 :
- 不需要写配置类
- 使用逗号分割,一行配置,即可完成多个数值的注入,配置文件更加精简
缺点 :
- 业务代码中数组使用很少,基本需要将其转换为 List,去做 contains、foreach 等操作。
三、替代方法
那么我们有没有办法,在解析 list、map 这些类型时,像数组一样方便呢?
答案是可以的,这就依赖于 EL
表达式。
3.1 解析 List
以使用 .yml
文件为例,我们只需要在配置文件中,跟配置数组一样去配置:
test:
list: aaa,bbb,ccc
在调用时,借助 EL
表达式的 split()
函数进行切分即可。
@Value("#{'${test.list}'.split(',')}")
private List<String> testList;
同样,为它加上默认值,避免不配置这个 key 时候程序报错:
@Value("#{'${test.list:}'.split(',')}")
private List<String> testList;
但是这样有个问题,当不配置该 key 值,默认值会为空串,它的 length = 1(不同于数组,length = 0),这样解析出来 list 的元素个数就不是空了。
这个问题比较严重,因为它会导致代码中的判空逻辑执行错误。这个问题也是可以解决的,在 split()
之前判断下是否为空即可。
@Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}")
private List<String> testList;
如上所示,即为最终的版本,它具有数组方式的全部优点,且更容易在业务代码中去应用。
3.2 解析 Set
解析 Set 和解析 List 本质上是相同的,唯一的区别是 Set 会做去重操作。
test:
set: 111,222,333,111
@Value("#{'${test.set:}'.empty ? null : '${test.set:}'.split(',')}")
private Set<Integer> testSet;
// output: [111, 222, 333]
3.3 解析 Map
解析 Map 的写法如下所示,value 为该 map 的 JSON 格式,注意这里使用的引号:整个 JSON 串使用引号包裹,value 值使用引号包裹。
test:
map1: '{"name": "zhangsan", "sex": "male"}'
map2: '{"math": "90", "english": "85"}'
在程序中,利用 EL 表达式注入:
@Value("#{${test.map1}}")
private Map<String,String> map1;
@Value("#{${test.map2}}")
private Map<String,Integer> map2;
注意,使用这种方式,必须得在配置文件中配置该 key 及其 value。我在网上找了许多资料,都没找到利用 EL 表达式支持不配置 key/value 的写法。
如果你真的很需要这个功能,就得自己写解析方法了,这里以使用 fastjson 进行解析为例:
(1) 自定义解析方法
public class MapDecoder {
public static Map<String, String> decodeMap(String value) {
try {
return JSONObject.parseObject(value, new TypeReference<Map<String, String>>(){});
} catch (Exception e) {
return null;
}
}
}
(2) 在程序中指定解析方法
@Value("#{T(com.github.jitwxs.demo.MapDecoder).decodeMap('${test.map1:}')}")
private Map<String, String> map1;
@Value("#{T(com.github.jitwxs.demo.MapDecoder).decodeMap('${test.map2:}')}")
private Map<String, String> map2;
四、避坑指南
以上就是本文的全部内容,利用 EL 表达式、甚至是自己的解析方法,可以让我们更加方便的配置和使用 Collection 类型的配置文件。
特别注意的是 @Value
注解不能和 @AllArgsConstructor
注解同时使用,否则会报错
Consider defining a bean of type 'java.lang.String' in your configuration
这种做法唯一不优雅的地方就是,这样写出来的 @Value
的内容都很长,既不美观,也不容易阅读。
测试项目
1.新建springboot项目整合web依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot-@value</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-demo</name>
<description>测试springboot中@value注解的使用</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.example.springbootdemo.SpringbootDemoApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.测试配置文件
说明:
springboot配置文件有两种格式 , 为了测试全面 , 我们两种配置文件都进行测试
注意: application.yml在项目的test目录下
application.properties
server.port=8080
# ²âÊÔ1
test.list[0]=aaa
test.list[1]=bbb
test.list[2]=ccc
# ²âÊÔ2
#test.array1=aaa,bbb,ccc
test.array2=111,222,333
test.array3=11.1,22.2,33.3
# ²âÊÔ3
test.list1=aaa,bbb,ccc
#test.list2=aaa,bbb,ccc
#test.list3=aaa,bbb,ccc
# ²âÊÔ4
test.set=111,222,333,111
# ²âÊÔ5
test.map1={"name": "zhangsan", "sex": "male"}
test.map2={"math": "90", "english": "85"}
#test.map3='{"name": "zhangsan", "sex": "male"}'
#test.map4='{"math": "90", "english": "85"}'
application.yml
server:
port: 8080
# 测试1
test:
list:
- aaa
- bbb
- ccc
# 测试2
array1: aaa,bbb,ccc
array2: 111,222,333
array3: 11.1,22.2,33.3
# 测试3
list1: aaa,bbb,ccc
list2: aaa,bbb,ccc
# list3: aaa,bbb,ccc
# 测试4
set: 111,222,333,111
# 测试5
map1: '{"name": "zhangsan", "sex": "male"}'
map2: '{"math": "90", "english": "85"}'
# map3: '{"name": "zhangsan", "sex": "male"}'
# map4: '{"math": "90", "english": "85"}'
3.map默认值配置类
package com.example.springbootdemo.demos.web;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class MapDecoder {
public static final ObjectMapper OBJECT_MAPPER;
static{
OBJECT_MAPPER = new ObjectMapper();
}
public static Map<String, String> decodeMap(String value) {
try {
// return JSONObject.parseObject(value, new TypeReference<Map<String, String>>(){});
return OBJECT_MAPPER.readValue(value,Map.class);
} catch (Exception e) {
return null;
}
}
}
4.测试功能
R
package com.example.springbootdemo.demos.web;
import java.util.HashMap;
import java.util.Map;
/**
* 返回数据
*
* @author Mark sunlightcs@gmail.com
*/
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
// private Integer code;
// private String msg;
// private Object data;
public R() {
put("code", 0);
}
public static R error() {
return error(500, "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(500, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map<String, Object> map) {
R r = new R();
r.putAll(map);
return r;
}
public static R ok() {
return new R();
}
public R put(String key, Object value) {
super.put(key, value);
return this;
}
}
测试@ConfigurationProperties配置类
package com.example.springbootdemo.demos.web;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
@ConfigurationProperties("test")
public class TestListConfig {
private List<String> list;
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
测试的controller
package com.example.springbootdemo.demos.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @ClassName: HelloController
* @Author: 邵明
* @Date: 2021/9/6 19:33
* @Description:
*/
@RestController
public class HelloController {
/**
* 测试1
*/
// @Value("${test.list}") //这种方式获取不到,报错BeanCreationException
// private List<String> testList;
@Autowired
TestListConfig testList;
@GetMapping("/test1")
public R test1() {
List<String> list = testList.getList();
return R.ok().put("data", list);
}
/**
* 测试2
*/
/*
仅仅多了一个 : 号,冒号后的值表示当 key 不存在时候使用的默认值,使用默认值时数组的 length = 0。
*/
@Value("${test.array1:}")
private String[] testArray1;
@Value("${test.array2}")
private int[] testArray2;
@Value("${test.array3}")
private double[] testArray3;
@GetMapping("/test2")
public R test2() {
return R.ok().put("testArray1", testArray1).put("testArray2", testArray2).put("testArray3", testArray3);
}
/**
* 测试3
*/
@Value("#{'${test.list1}'.split(',')}")
private List<String> list1;
@GetMapping("/test31")
public R test31() {
return R.ok().put("list1", list1);
}
/*
测试配置文件没有并设置默认值
list2: [""] 这样的结果不符合空集合
list:[] 应该返回这样的结果
但是这样有个问题,当不配置该 key 值,默认值会为空串,它的 length = 1(不同于数组,length = 0),这样解析出来 list 的元素个数就不是空了。
*/
@Value("#{'${test.list2:}'.split(',')}")
private List<String> list2;
@GetMapping("/test32")
public R test32() {
return R.ok().put("list2", list2);
}
/*
即为最终的版本,它具有数组方式的全部优点,且更容易在业务代码中去应用。
*/
@Value("#{'${test.list3:}'.empty ? null : '${test.list3:}'.split(',')}")
private List<String> list3;
@GetMapping("/test33")
public R test33() {
return R.ok().put("list3", list3);
}
/**
* 测试4 (测试set)
*/
@Value("#{'${test.set:}'.empty ? null : '${test.set:}'.split(',')}")
private Set<Integer> testSet;
@GetMapping("/test4")
public R test4() {
return R.ok().put("testSet", testSet);
}
/**
* 测试5 (测试map)
*/
@Value("#{${test.map1}}")
private Map<String,String> map1;
@Value("#{${test.map2}}")
private Map<String,Integer> map2;
@GetMapping("/test51")
public R test51() {
return R.ok().put("map1", map1)
.put("map2",map2);
}
/*
* EL 表达式支持不配置 key/value 的写法。
* 需要结合配置类MapDecoder(自定义json序列化规则)
*/
@Value("#{T(com.example.springbootdemo.demos.web.MapDecoder).decodeMap('${test.map3:}')}")
private Map<String, String> map3;
@Value("#{T(com.example.springbootdemo.demos.web.MapDecoder).decodeMap('${test.map4:}')}")
private Map<String, String> map4;
@GetMapping("/test52")
public R test52() {
return R.ok().put("map3", map3)
.put("map4",map4);
}
}
测试项目仓库地址
https://gitee.com/shao_ming314/springboot-value
个人博客网址:www.shaoming.club