- 在resources文件下创建新的配置文件,如test.yml:
es:
name: elasticsearch
- 准备使用@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);
}
}
- 创建实体类:
@PropertySource(value = {"classpath:test.yml"}, factory = PropertySourceConfig.class)
@Component
@ConfigurationProperties(prefix = "es")
@Setter
@Getter
public class EsParams {
private String name;
}
- 以上已经完成,以下为测试:
@SpringBootTest
@RunWith(SpringRunner.class)
class EsParamsTest {
@Resource
private EsParams esParams;
@Test
void testParams() {
Assertions.assertEquals("elasticsearch", esParams.getName());
}
}