Springboot读取自定义属性之集合(list,数组)

springboot配置文件的读取操作很常见,之前也写过简单的读取配置文件的笔记SpringBoot学习之DAY_02 springboot配置文件信息读取
这篇笔记主要记录下最近在读取配置文件当中的心得和新知识点吧。

如何读取配置文件当中自定义的集合属性

很少在配置文件当中自定义数组属性,最近刚好遇到并记录下

1 创建自定义数组配置

在yml文件当中新建如下自定义配置属性

fastboot:
  request:
    allow:
      - /login
      - /actuator/**
      - /druid/**

2 通过实体类接收配置文件

/**
 * @author 海加尔金鹰
 * @apiNote 读取项目自定义的配置信息
 * @since 2020/9/11
 **/
@Configuration
@ConfigurationProperties(prefix = "fastboot")
public class FastBootConfig {
    /**
     * 描述: prefix = "fastboot" 配置表示读取配置文件当中fastboot开头的配置
     * request 属性对应配置文件当中的request  保持同名原则
     **/
    private Map<String, List<String>> request = new HashMap<>();

    public Map<String, List<String>> getRequest() {
        return request;
    }

    public void setRequest(Map<String, List<String>> request) {
        this.request = request;
    }
}

获取配置属性在项目当中使用

@SpringBootTest
class FastBootApplicationTests {
	//通过spring注入
    @Autowired
    FastBootConfig config;

    @Test
    public void getAllow() {
        Map<String, List<String>> request = config.getRequest();
        //获取到request 当中的allow数组
        List<String> allow = request.get("allow");
        System.out.println(allow.toString());
    }
}

总结

读取

猜你喜欢

转载自blog.csdn.net/ycf921244819/article/details/108537338