Java教程:如何使用yml文件配置数组列表到java配置类中

本文详细介绍了在SpringBoot应用中,如何通过`@ConfigurationProperties`注解从YML文件中配置并注入一个多值列表(如数组)的示例,包括创建配置类、属性类和对应的YML配置,以及在代码中实际使用的例子。
摘要由CSDN通过智能技术生成

–在以往我们讲过通过@Value或@ConfigurationProperties的方式注入yml文件中的配置,今天给大家讲一下如何配置多个列表,比如数组的方式注入yml配置,相当于一个List,对特殊业务情况下非常有用,接下来就具体列一下实现步骤。

一、 创建一个配置类

/**
 * 配置类
 * @author wfeil211@foxmail.com
 */
@Configuration
@EnableConfigurationProperties(TableListPropertie.class)
public class TableListConfig {
}

二、 创建一个属性类

/**
 * 属性类
 * @author wfeil211@foxmail.com
 */
@Data
@ConfigurationProperties(prefix = "config.table")
public class TableListPropertie {
    private List<TableList> tableList;
}

三、 创建一个TableList类

/**
 * 参数类
 * @author wfeil211@foxmail.com
 */
@Data
public class TableList {

    /** 表名 */
    private String tableName;

    /** 表备注 */
    private String tableRemark;
}

四、 yml配置

#配置
config:
  #表集合
  table:
    tableList:
      - tableName: "表名"
        tableRemark: "表备注"

五、 具体使用方法

@Autowired
private TableListPropertie tableListPro;

@GetMapping("/test")
public void test(){
	log.info(tableListPro.getTableList().get(0).getTableName());
}

本次教程到这里就结束了,希望大家多多关注支持(首席摸鱼师 微信同号),持续跟踪最新文章吧~

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在application.yml配置list时,需要使用"-"来组成一个列表集合。同时,属性名称在yml文件中支持连字符"-",比如"four-span",而在Java类中配置属性时需要转为驼峰式,如"fourSpan"。此外,还需要在Java类中配置set和get方法。可以使用@ConfigurationProperties注解来指定配置类的前缀,如@ConfigurationProperties(prefix = "demo.code")。另外,在配置类中需要使用@Configuration注解标记该类为配置类,并使用@Getter和@Setter注解为属性生成get和set方法。在配置类中,可以定义一个List属性来接收yml文件中的列表值。例如,可以创建一个配置类Config,其中包含一个paramInfo属性用来接收列表值,代码如下: ```java @Configuration @ConfigurationProperties(prefix = "demo.code") @Getter @Setter public class Config { private List<ParamInfo> paramInfo; } ``` 这样,通过读取application.yml文件中的配置,并将列表值注入到Config类的paramInfo属性中,以便在应用程序中使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [springboot读取yml文件中的list列表数组、map集合和对象](https://blog.csdn.net/weixin_42274846/article/details/128155678)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [springboot的application.yml如何配置List、Map形式的配置](https://blog.csdn.net/Hope_lee/article/details/105660434)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值