0


Spring Boot 优雅配置yml配置文件定义集合、数组和Map

一、@value 获取配置文件

在平时的yml配置文件中,我们经常使用到配置基本数据类型的字符串,比如配置日志文件的写法如下:

# 配置日志输出级别logging:# 指定logback配置文件的位置 config: classpath:logback-spring.xml
  # 文件日志要输出的路径path: E:/logs/springboot_server
  # 日志的输出级别level:root: info

获取属性值的话可以通过@value 注解来实现,如下:

@Value("${logging.path}")privateString path;// 获取日志文件的输出路径

二、 List集合获取配置文件

第一种方法

# 拦截器路径拦截或者不拦截配置interceptorconfig:path:#该路径下任何类型请求均拦截include:- /api/v1/token/api_token
      - /api/v1/yibaotong/save

第二种方法

# 拦截器路径拦截或者不拦截配置interceptorconfig:path:#该路径下任何类型请求均拦截include:[/api/v1/token/api_token,/api/v1/yibaotong/save]

总结

这里需要注意的是,定义List集合不能用

@value

注解来获取List集合的所有值,需要定义一个配置类bean,然后使用

@ConfigurationProperties

注解来获取list集合值,做法如下:

@Data@Component@ConfigurationProperties(prefix ="interceptorconfig.path")// 配置文件的前缀publicclassInterceptorPathBean{/*
     * 需要拦截的路径
     */privateList<String> include;}

三、定义对象list集合获取配置文件

单个对象List

首先创建一个user对象如下:

@DatapublicclassUserimplementsSerializable{privatestaticfinallong serialVersionUID =1L;privateString appId;privateString password;}

然后yml配置文件的写法如下:

jwt:userlist:-appId: YiBaoTong
      password:123456-appId: ZhiKe
      password:123456

定义配置bean使用@ConfigurationProperties注解获取对象集合值:

@Data@Component@ConfigurationProperties(prefix ="jwt")// 配置 文件的前缀publicclassJwtConfigBean{/**
     * 用户列表
     */privateList<User> userlist;}

List对象中包含List

定义配置bean使用@ConfigurationProperties注解获取对象集合值:

@Data@Component@ConfigurationProperties(prefix ="jwt")// 配置 文件的前缀publicclassJwtConfigBean{/**
     * 用户列表
     */privateList<UserTest> userList;@DataprivatestaticclassUserTest{privateString appId;privateList<String> passwordList;}}

yml 文件配置

jwt:userList:-appId:'121212'passwordList:'活动时间流程节点-PromoTimeValidNode,活动时间流程节点-PromoTimeValidNode2'-appId:'werw3313'passwordList:'活动时间流程节点-PromoTimeValidNode,活动时间流程节点-PromoTimeValidNode2'

四、数组获取配置文件

yaml 格式如下:

interceptorconfig:path:includes: /api/v1,/api/v2  #注意要用逗号分隔开

可以通过@value注解获取数组值,如下:

@Value("${interceptorconfig.path.includes}")privateString[] includes;

也可以通过创建配置类bean,使用@ConfigurationProperties注解获取,如下:

@Data@Component@ConfigurationProperties(prefix ="interceptorconfig.path")// 配置 文件的前缀publicclassInterceptorPathBean{privateString[] includes;}

五、定义Map集合配置文件

yaml 格式如下:

interceptorconfig:path:maps:{name: 小明,age:24}

或者写成:

interceptorconfig:path:maps:name: 小明
      age:24

通过创建配置类bean,使用@ConfigurationProperties注解获取map值,如下:

@Data@Component@ConfigurationProperties(prefix ="interceptorconfig.path")// 配置 文件的前缀publicclassInterceptorPathBean{privateMap<String,String> maps;}

以上就是Spring Boot yml配置文件定义基本数据类型和引用数据类型的方式;

六、参考链接

spring boot 的yml配置文件定义list集合、数组和map以及使用中出现的错误_yml配置map类型的数据注入失败-CSDN博客


本文转载自: https://blog.csdn.net/zouliping123456/article/details/134080774
版权归原作者 给自己一个 smile 所有, 如有侵权,请联系我们删除。

“Spring Boot 优雅配置yml配置文件定义集合、数组和Map”的评论:

还没有评论