Loading

SpringBoot 读取配置文件

  1. 在resources文件下创建新的配置文件,如test.yml:
es:
  name: elasticsearch
  1. 准备使用@PropertySource注解来读取test.yml内容,但@PropertySource本身不支持yml文件,所以创建以下类:
public class PropertySourceConfig extends DefaultPropertySourceFactory {
    @Override
    @NonNull
    public PropertySource<?> createPropertySource(String name, @NonNull EncodedResource resource) throws IOException {
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}
  1. 创建实体类:
@PropertySource(value = {"classpath:test.yml"}, factory = PropertySourceConfig.class)
@Component
@ConfigurationProperties(prefix = "es")
@Setter
@Getter
public class EsParams {
    private String name;
}

  1. 以上已经完成,以下为测试:
@SpringBootTest
@RunWith(SpringRunner.class)
class EsParamsTest {

    @Resource
    private EsParams esParams;

    @Test
    void testParams() {
        Assertions.assertEquals("elasticsearch", esParams.getName());
    }
}
posted @ 2023-09-04 16:12  星流残阳  阅读(25)  评论(0编辑  收藏  举报