SpringBoot读取properties中配置的List集合

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Person {
    private String name;
    private String age;
    private String content;
}

@Component//将该类交由Spring管理
@ConfigurationProperties(prefix = "project") //自定义.properties文件的前缀
//指定.properties文件名与位置,字符集编码,.properties文件经常出现乱码,相对没有yml文件好
@PropertySource(value = "classpath:config.properties",encoding="UTF-8")
@Data//这里需要提供set方法
public class ProjectListVo {

    List<Person> plist;
}

比如现在控制器里自动装配

@Controller

public class TestController{

        @Resource

        private ProjectListVo projectListVo;//这样就有值了

        

}

config.properties中的内容

project.plist[0].name=zhangsan
project.plist[0].age=23
project.plist[0].content=哈哈

project.plist[1].name=lisi
project.plist[1].age=24
project.plist[1].content=呵呵

这里注意个小问题:

使用了 ConfigurationProperties 注解 会有这么一串提示

这串提示是要我们加个依赖(但是不加也无所谓)

这个依赖的作用是在properties文件中如下,会有下面这样的提示

 在pom.xml加上该依赖

警告消失(且在application.properties里出现.....其实这里配置的是另外一个config.properties,而这个出现在application.properties)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot ,可以使用 `@ConfigurationProperties` 注解来读取配置文件。当配置文件有一个以特定前缀开头的配置集合时,可以使用 `@ConfigurationProperties` 注解与 `@Bean` 注解结合使用来读取。 例如,假设我们有一个配置文件 `application.properties`,其包含以下配置项: ``` myapp.items[0].name=apple myapp.items[0].price=5 myapp.items[1].name=banana myapp.items[1].price=3 ``` 我们可以通过以下方式读取配置集合: 首先,我们需要创建一个 Java 类来表示每个配置项的属性。例如,我们可以创建一个 `Item` 类: ```java public class Item { private String name; private int price; // 省略 getter 和 setter 方法 } ``` 然后,我们可以创建一个 `ItemsConfiguration` 类来读取配置集合: ```java @Configuration @ConfigurationProperties(prefix = "myapp") public class ItemsConfiguration { private List<Item> items = new ArrayList<>(); public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } @Bean public List<Item> itemList() { return items; } } ``` 在上面的代码,我们使用 `@ConfigurationProperties` 注解来指定配置项的前缀为 `myapp`,并且定义了一个 `List<Item>` 类型的属性 `items` 来保存配置集合。我们还定义了一个 `itemList()` 方法,用于将 `items` 属性作为 Bean 注册到 Spring 容器。 最后,在需要使用该配置集合的地方,我们可以使用 `@Autowired` 注解来注入 `List<Item>` 类型的 Bean: ```java @RestController public class MyController { @Autowired private List<Item> items; @GetMapping("/items") public List<Item> getItems() { return items; } } ``` 这样就可以通过访问 `/items` 接口来获取配置集合了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hrui0706

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值