@PropertySource加载yml

1、yml文件通常是 application.yml

当我们需要新的yml文件时,新建一个yml文件 response.yml

  1. response:
  2. name: 张三

2、启动类新加

@PropertySource(value = {"classpath:response.yml"}, encoding = "utf-8", factory = ResponseFactory.class)

3、新增工厂类

  1. public class ResponseFactory extends DefaultPropertySourceFactory {
  2. @Override
  3. public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
  4. if (resource == null){
  5. return super.createPropertySource(name, resource);
  6. }
  7. List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
  8. return sources.get(0);
  9. }
  10. }

4、新建Response类

  1. @Component
  2. @Data
  3. public class Response {
  4. @Value("${response.name}")
  5. private String name;
  6. }

5、测试

  1. @Test
  2. public void test() {
  3. try{
  4. System.out.println("666555:"+response.getName());
  5. } catch (Exception e) {
  6. }
  7. }

控制台:666555:张三

(0)

相关推荐