SpringBoot 的@Value注解真是太强了,谁用谁说爽!

1、前言

在平常开发中,常常会遇到须要在配置文件中,存储 List 或是 Map 这种类型的数据。Spring 原生是支持这种数据类型的,以配置 List 类型为例,对于 .yml 文件配置以下:java

test:
  list:
    - aaa
    - bbb
    - ccc
复制代码

对于 .properties 文件配置以下所示:git

test.list[0]=aaa
test.list[1]=bbb
test.list[2]=ccc
复制代码

当咱们想要在程序中使用时候,想固然的使用 @Value 注解去读取这个值,就像下面这种写法同样:github

@Value("${test.list}")
private List<String> testList;
复制代码

你会发现程序直接报错了,报错信息以下:spring

java.lang.IllegalArgumentException: Could not resolve placeholder 'test.list' in value "${test.list}"
复制代码

这个问题也是能够解决的,以咱们要配置的 key 为 test.list 为例,新建一个 test 的配置类,将 list 做为该配置类的一个属性:json

@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();
复制代码

能够看见,这种方式十分的不方便,最大的问题是配置和代码高耦合了,增长一个配置,还须要对配置类作增减改动。markdown

整理的spring学习笔记分享给你们:176页Spring学习笔记,完整版数据结构

2、数组怎么样

数组?说实话,业务代码写多了,这个“古老”的数据结构远远没有 list 用的多,可是它在解决上面这个问题上,出乎异常的好用。ide

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 等操做。

3、替代方法

那么咱们有没有办法,在解析 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;
复制代码

4、后续

以上就是本文的所有内容,利用 EL 表达式、甚至是本身的解析方法,可让咱们更加方便的配置和使用 Collection 类型的配置文件。特别注意的是 @Value 注解不能和 @AllArgsConstructor 注解同时使用,不然会报错

Consider defining a bean of type 'java.lang.String' in your configuration
复制代码

这种作法惟一不优雅的地方就是,这样写出来的 @Value 的内容都很长,既不美观,也不容易阅读。

相关文章
相关标签/搜索