1:spring-boot启动类
@SpringBootApplication
@EnableConfigurationProperties({YmlConfig.class})
public class ReadApplication {
public static void main(String[] args) {
SpringApplication.run(ReadApplication.class, args);
}
}
2:yml配置文件
ws: #自定义的属性和值
simpleProp: simplePropValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Vavlue2
mapProps:
key1: value1
key2: value2
3:读取yml配置文件的类。
@ConfigurationProperties(prefix="ws") //application.yml中的ws下的属性
public class YmlConfig {
private String simpleProp;
private String[] arrayProps;
private List<Map<String, String>> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
private List<String> listProp2 = new ArrayList<>(); //接收prop2里面的属性值
private Map<String, String> mapProps = new HashMap<>(); //接收prop1里面的属性值
}
4:单元测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ReadApplication.class)
public class ReadApplicationYmlTests {
@Autowired
private YmlConfig ymlConfig;
@Test
public void testDisplayYmlValue() throws JsonProcessingException {
System.out.println("simpleProp: " + ymlConfig.getSimpleProp());
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("arrayProps: " + objectMapper.writeValueAsString(ymlConfig.getArrayProps()));
System.out.println("listProp1: " + objectMapper.writeValueAsString(ymlConfig.getListProp1()));
System.out.println("listProp2: " + objectMapper.writeValueAsString(ymlConfig.getListProp2()));
System.out.println("mapProps: " + objectMapper.writeValueAsString(ymlConfig.getMapProps()));
}
}
5:控制台输出的测试内容:
simpleProp: simplePropValue
arrayProps: ["1","2","3","4","5"]
listProp1: [{"name":"abc","value":"abcValue"},{"name":"efg","value":"efgValue"}]
listProp2: ["config2Value1","config2Vavlue2"]
mapProps: {"key1":"value1","key2":"value2"}