关于java:Spring-配置文件字段注入到ListMap

9次阅读

共计 1944 个字符,预计需要花费 5 分钟才能阅读完成。

明天给大家分享冷门然而有很实小常识,Spring 配置文件注入 list、map、字节流。

list 注入

properties 文件

user.id=3242,2323,1

应用 spring el 表达式

@Value(“#{‘${user.id}’.split(‘,’)}”)

private List<Integer> list;

yaml 文件

在 yml 配置文件配置数组形式

number:
  arrays: 
    - One
    - Two
    - Three

@Value(“${number.arrays}”)
private List list

尽管网上都说,这样能够注入,我亲自实际过了,必定是不能的。会抛出 Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'number.arrays' in value "${number.arrays}"异样。要想注入必须要应用@ConfigurationProperties

@ConfigurationProperties(prefix = "number")
public class AgentController {

    private List arrays;
    public List getArrays() {return arrays;}

    public void setArrays(List arrays) {this.arrays = arrays;}
    @GetMapping("/s")
    public List lists(){return arrays;}

不是想这么麻烦,能够像 properties 文件写法,应用 el 表达式即可

number:
  arrays: One,Two,Three

@Value(“#{‘${number.arrays}’.split(‘,’)}”)

private List arrays;

注入文件流

    @Value("classpath: application.yml")
    private Resource resource;
   
    //  占位符
    @Value("${file.name}")
    private Resource resource2;

    @GetMapping("/s")
    public String lists() throws IOException {return IOUtils.toString(resource.getInputStream(),"UTF-8");
    }

从类门路加载 application.yml 文件将文件注入到 org.springframework.core.io.Resource,能够应用 getInputStream() 办法获取流。比起应用类加载器获取门路再去加载文件的形式,优雅、简略不少。

Map Key Value 注入

properties

resource.code.mapper={x86:”hostIp”}

@Value(“#{${resource.code.mapper}}”)

private Map<String, String> mapper;

胜利注入

yaml

在 yaml 文件中,应用 @Value 不能注入 Map 实例的,要借助@ConfigurationProperties 能力实现。

@ConfigurationProperties(prefix = "blog")
public class AgentController {

    private Map website;

    public Map getWebsite() {return website;}

 public void setWebsite(Map website) {this.website = website;}

    @GetMapping("/s")
    public String lists() throws IOException {return JsonUtil.toJsonString(website);
    }

配置文件

blog:
  website:
    juejin: https://juejin.im
    jianshu: https://jianshu.com
    sifou: https://segmentfault.com/

能够看出 @ConfigurationProperties 注入性能远比 @Value 强,不仅能注入 List、Map 这些,还能注入对象属性,动态外部类属性,这个在 Spring Boot Redis 模块 org.springframework.boot.autoconfigure.data.redis.RedisProperties体现进去。

区别

区别 @ConfigurationProperties @Value
类型 各种复制类型属性 Map、外部类 只反对简略属性
spEl 表达式 不反对 反对
JSR303 数据校验 反对 不反对
性能 一个列属性批量注入 单属性注入

正文完
 0