java 读取配置文件中的列表

使用场景:

    配置文件为yml

简单的字符串列表

```
test: 
    - account1
    - account2
    - account3
```

在java中,需要使用

config初始化的时候

List<String> test = new ArrayList<String>();

如果里面的列表是一个复杂的,则需要注意写法

```
test:
    - user:
        name: 111
        password: 2222
    - user:
        name: aaaa
        password: bbbb
    - user:
        name: a1
        password: b1111
```

注意: 每个冒号后面需要加个空格,否则可能会出现读取不到列表

定义一个account的class

POM.xml添加

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

import lombok.Data;

@Data
public class Account {
    private String name;
    private String password;
}

然后再


@Component
@ConfigurationProperties( prefix="test" )
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

@Data
public class TestConfig {
    private List<Account> accounts;
}

然后使用TestConfig的时候,就能正常加载

猜你喜欢

转载自my.oschina.net/u/1538135/blog/1547481