springboot读取自定义配置文件的list集合
1、新建自定义配置文件
文件名:opcaccess.yaml
内容:
opc: accesslist: - Channel1.Device1.Tag1 - Channel1.Device1.Tag2 - Channel1.Device1.test # 字段1 - test1 - 业务意义
pom.xml引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、自定义配置文件对应的bean类
@Configuration @ConfigurationProperties(prefix = "opc") @PropertySource(value="classpath:opcaccess.yaml",ignoreResourceNotFound = false,factory = MyPropertySourceFactory.class)//配置文件路径 public class OpcAccessConfig { private List<String> accesslist; public List<String> getAccesslist() { return accesslist; } public void setAccesslist(List<String> accesslist) { this.accesslist = accesslist; } }
3、新建工厂转换类PropertySourceFactory,把自定义配置文件.yml的读取方式变成跟application.yml的读取方式一致
public class MyPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { return new YamlPropertySourceLoader().load(name,resource.getResource()).get(0); } }
4、调用
public List<ResultBean> readPLCWithFile() throws Exception { // 1、获取配置文件中的待读取字段 List<String> opcAccessList = opcAccessConfig.getAccesslist(); List<ResultBean> resultBeans = opcUaService.readPLCWithFile(opcAccessList); for(ResultBean result : resultBeans){ System.out.println(result); } return resultBeans; }