Spring 文件字段注入到List、Map Spring 配置文件字段注入到List、Map

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring 文件字段注入到List、Map Spring 配置文件字段注入到List、Map

xiaowu6666   2021-03-15 我要评论
想了解Spring 配置文件字段注入到List、Map的相关内容吗,xiaowu6666在本文为您仔细讲解Spring 文件字段注入到List、Map的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring,文件字段注入,Spring,字段注入到List,Spring,,字段注入到Map,下面大家一起来学习吧。

今天给大家分享冷门但是有很实小知识,Spring 配置文件注入list、map、字节流。

list 注入

properties文件

user.id=3242,2323,1

使用spring el表达式

 @Value("#{'${user.id}'.split(',')}")
private List 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数据校验 支持 不支持
功能 一个列属性批量注入 单属性注入

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们