springboot读取properties配置的集合
时间: 2023-11-16 18:10:30 浏览: 84
在 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` 接口来获取配置项集合了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)