@value读取yml
时间: 2023-07-06 13:33:09 浏览: 188
您可以使用Spring框架提供的YamlPropertySourceLoader类来读取YAML文件。以下是一个示例:
```java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.core.io.support.YamlPropertySourceLoader;
import java.io.IOException;
@Configuration
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:config.yml")
public class Config {
@Value("${foo.bar}")
private String fooBar;
public String getFooBar() {
return fooBar;
}
public static class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Resource yamlResource = new ClassPathResource(resource.getResource().getFilename());
if (yamlResource.exists()) {
return new ResourcePropertySource(name, loadYaml(yamlResource));
}
return null;
}
private org.springframework.core.env.PropertySource<?> loadYaml(Resource yamlResource) throws IOException {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
org.springframework.core.env.PropertySource<?> propertySource = loader.load(yamlResource.getFilename(), yamlResource).get(0);
return propertySource;
}
}
}
```
在这个示例中,我们使用@Configuration注释来指示这是一个配置类。我们还使用@PropertySource注释来指定要加载的YAML文件和它的位置。我们还使用@Value注释来注入foo.bar属性的值。最后,我们使用YamlPropertySourceLoader类来加载YAML文件。
阅读全文