You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot读取YAML中Map<String,List<String>>配置失败的解决方法

问题描述

在网关中为不同应用配置登录校验白名单,YAML配置如下:

dolphin:
  gateway:
    login-check-path:
      exclude:
        app1:
          - /login
          - /signin
        app2:
          - /login1
          - /signin1

期望将exclude读取为Map<String, List<String>>结构,但目前读取到的exclude为空。尝试了两种配置类写法均未解决:

  • 第一种配置类初始化了空HashMap,但无标准getter;
  • 第二种添加了@PropertySource指定配置文件路径并补充了setter,仍无效。

启动类已添加@EnableConfigurationProperties({LoginExcludeUrl.class})。

解决方案

1. 修复配置类的Getter/Setter方法

Spring Boot的@ConfigurationProperties依赖标准JavaBean规范绑定配置:

  • 必须为exclude字段提供无参数的getExclude()方法(返回整个Map),而非带参数的自定义方法;
  • 提供对应的setExclude()方法,或使用Lombok的@Data注解自动生成。

2. 移除@PropertySource注解

@PropertySource默认不支持YAML格式配置文件,Spring Boot会自动加载classpath:application.yaml,无需额外指定该注解。

正确的配置类代码

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author xiaoqiangjiang
 */
@ConfigurationProperties(prefix = "dolphin.gateway.login-check-path")
@Component
public class LoginExcludeUrl {

    private Map<String, List<String>> exclude;

    // 标准getter,返回整个Map
    public Map<String, List<String>> getExclude() {
        return exclude;
    }

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

    // 自定义方法,根据appKey获取对应的路径列表
    public List<String> getExcludePaths(String appKey) {
        return exclude != null ? exclude.get(appKey) : null;
    }
}

3. 验证配置绑定

可通过编写测试类或Controller验证配置是否正确加载:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private LoginExcludeUrl loginExcludeUrl;

    @GetMapping("/test")
    public void testConfig() {
        System.out.println("app1的白名单路径:" + loginExcludeUrl.getExcludePaths("app1"));
        System.out.println("app2的白名单路径:" + loginExcludeUrl.getExcludePaths("app2"));
        System.out.println("完整的exclude Map:" + loginExcludeUrl.getExclude());
    }
}

额外说明

  • 若不想使用@Component,可移除该注解,仅保留@ConfigurationProperties,然后在启动类的@EnableConfigurationProperties中指定该类即可;
  • 确保application.yaml文件放置在src/main/resources目录下,Spring Boot能正确扫描到。

内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:22:40