springboot注入yml list报错 springboot注入yml配置文件 list报错的解决方案

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

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

springboot注入yml list报错 springboot注入yml配置文件 list报错的解决方案

风舞叶扬   2021-08-18 我要评论
想了解springboot注入yml配置文件 list报错的解决方案的相关内容吗,风舞叶扬在本文为您仔细讲解springboot注入yml list报错的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springboot配置文件,注入yml配置文件,list报错,下面大家一起来学习吧。

springboot注入yml配置文件 list报错

springboot中yml配置注入一般使用@Value注解可注入String类型数据,比如:

@Value("${config}")
String stringConfig;

即可注入属性,而注入list使用此方法则会报错提示Could not resolve placeholder xxx。

注入list的正确方法

配置文件实例

list-config:
  config:
    - companyId
    - userId
    - originId

注入姿势

@ConfigurationProperties(prefix = "list-config")
@Component
@Setter
public class VisitorSourceController implements VisitorSourceApi { 
    List<String> config; 
}

注意:必须在类上添加Lombok的@Setter注解或者加上属性set方法,否则config属性会获取到null。

springboot yml 配置文件注入Map,List

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: 小狗
      age: 12
/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
 
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
 
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

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

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