SpringBoot在application.properties配置列表并在Controller读取校验
Spring Boot配置列表读取+参数校验实现方案
1. application.properties中声明值列表
Spring Boot原生支持逗号分隔的集合类型配置,不需要额外做特殊格式定义,直接按如下方式编写即可,框架会自动识别为列表结构:
# 合法值列表,多个值用英文逗号分隔 com.mail=aaaa,bbbb,cccc
如果编写时不小心在逗号前后加了空格,框架注入时会自动去除每个元素前后的空白字符,不需要额外处理。
2. Controller中读取配置列表
最简单的方式是直接用@Value注解注入,Spring会自动将逗号分隔的配置值转换为List<String>类型,不需要手动拆分字符串:
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/response") public class HomeController { // 直接注入配置的合法值列表 @Value("${com.mail}") private List<String> allowedValues; // 接口方法省略 }
如果后续同组配置项会扩展,也可以用@ConfigurationProperties批量绑定,当前单列表场景用@Value足够,不需要额外写配置类。
3. 参数匹配校验逻辑实现
不需要手动编写循环遍历列表,直接调用List自带的contains()方法即可,方法底层已经实现了遍历匹配逻辑,代码更简洁:
@PostMapping("/postbody") public String postBody(@RequestBody String fullName) { // 判断传入参数是否在合法值列表中 if (!allowedValues.contains(fullName)) { return "传入参数不合法"; } // 下方写正常业务逻辑 return "校验通过,接收到的参数为:" + fullName; }
如果需要做忽略大小写的匹配,可以用Stream流的anyMatch方法实现:
boolean isMatch = allowedValues.stream() .anyMatch(item -> item.equalsIgnoreCase(fullName)); if (!isMatch) { return "传入参数不合法"; }
上述校验逻辑对@RequestParam接收的Query参数、@PathVariable接收的路径参数同样适用,不需要做逻辑修改,GET接口示例:
@GetMapping("/query") public String queryParam(@RequestParam String fullName) { if (!allowedValues.contains(fullName)) { return "传入参数不合法"; } return "校验通过,接收到的参数为:" + fullName; }
提示:如果配置的值是数字、布尔等其他类型,只需要将注入的List泛型改为对应类型即可,Spring会自动做类型转换。
内容的提问来源于stack exchange,提问作者justina antony
相关产品推荐
相关产品推荐

