zoukankan      html  css  js  c++  java
  • SpringBoot 的@Value注解太强大了,用了都说爽!

    一、前言

    在日常开发中,经常会遇到需要在配置文件中,存储 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 等操作。

    https://mp.weixin.qq.com/s/2PmATTS_SJGarsqDLDLpTQ

    故乡明
  • 相关阅读:
    HTTP响应状态码
    跨域
    第一章-极限与函数
    离群点检测
    关联规则(初识)
    python分类预测模型的特点
    分类预测算法评价(初识)
    人工神经网络(初识)
    决策树(初识)
    挖掘建模
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/15292141.html
Copyright © 2011-2022 走看看