@PropertySource只對properties文件可以進行加載,但對於yml或者yaml不能支持。
// 繼承DefaultPropertySourceFactory
public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null) {
return super.createPropertySource(name, resource);
}
Resource resourceResource = resource.getResource();
if (!resourceResource.exists()) {
return new PropertiesPropertySource(null, new Properties());
} else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource);
return sources.get(0);
}
return super.createPropertySource(name, resource);
}
}
@Component
@Data
@PropertySource(value = {"classpath:person.yaml"}, factory = YamlAndPropertySourceFactory.class)
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
private String name;
private String age;
private Map<String, Object> properties;
private List<Object> item;
}