@PropertySource 本身 仅 支持 .properties 格式的文件,后缀可以不为 .properties,但是内容格式得按照 .properties 的格式来。
例如:
my.properties
1 2 3 4 5 6 7 8 9 10
|
@PropertySource(value = "classpath:my.properties")
@PropertySource(value = "classpath:my.yml")
|
如果想要 @PropertySource 读取 .yml 格式的文件需要自定义 YamlPropertySourceFactory
1 2 3
| myy: name: lixifun age: 88
|
使用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource;
@Data @Configuration @ConfigurationProperties(prefix = "myy") @PropertySource(value = "classpath:my.yml", factory = YamlPropertySourceFactory.class) public class MyYamlConfig {
private String name; private Integer age;
}
|
YamlPropertySourceFactory.java 的代码内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
Resource resource = encodedResource.getResource();
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource);
Properties props = factory.getObject();
return new PropertiesPropertySource(resource.getFilename(), props); } }
|