Java 如何使用 YamlPropertiesFactoryBean 使用 Spring Framework 4.1 加载 YAML 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28303758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use YamlPropertiesFactoryBean to load YAML files using Spring Framework 4.1?
提问by ktulinho
I have a spring application that is currently using *.properties files and I want to have it using YAML files instead.
我有一个当前使用 *.properties 文件的 spring 应用程序,我想使用 YAML 文件来代替它。
I found the class YamlPropertiesFactoryBeanthat seems to be capable of doing what I need.
我发现YamlPropertiesFactoryBean类似乎能够做我需要的事情。
My problem is that I'm not sure how to use this class in my Spring application (which is using annotation based configuration). It seems I should configure it in the PropertySourcesPlaceholderConfigurerwith the setBeanFactorymethod.
我的问题是我不确定如何在我的 Spring 应用程序中使用这个类(它使用基于注释的配置)。看来我应该使用 setBeanFactory方法在PropertySourcesPlaceholderConfigurer 中配置它。
Previously I was loading property files using @PropertySourceas follows:
以前我使用@PropertySource加载属性文件,如下所示:
@Configuration
@PropertySource("classpath:/default.properties")
public class PropertiesConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
How can I enable the YamlPropertiesFactoryBean in the PropertySourcesPlaceholderConfigurer so that I can load YAML files directly? Or is there another way of doing this?
如何在 PropertySourcesPlaceholderConfigurer 中启用 YamlPropertiesFactoryBean 以便我可以直接加载 YAML 文件?或者有另一种方法吗?
Thanks.
谢谢。
My application is using annotation based config and I'm using Spring Framework 4.1.4. I found some information but it always pointed me to Spring Boot, like this one.
我的应用程序使用基于注释的配置,我使用的是 Spring Framework 4.1.4。我找到了一些信息,但它总是将我指向 Spring Boot,就像这个。
采纳答案by turtlesallthewaydown
With XML config I've been using this construct:
使用 XML 配置我一直在使用这个构造:
<context:annotation-config/>
<bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
<property name="resources" value="classpath:test.yml"/>
</bean>
<context:property-placeholder properties-ref="yamlProperties"/>
Of course you have to have the snakeyaml dependency on your runtime classpath.
当然,您必须在运行时类路径上拥有snakeyaml 依赖项。
I prefer XML config over the java config, but I recon it shouldn't be hard to convert it.
我更喜欢 XML 配置而不是 java 配置,但我认为转换它应该不难。
edit:
java config for completeness sake
编辑:
为了完整起见,java配置
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("default.yml"));
propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
return propertySourcesPlaceholderConfigurer;
}
回答by ayurchuk
To read .yml file in Spring you can use next approach.
要在 Spring 中读取 .yml 文件,您可以使用下一种方法。
For example you have this .yml file:
例如你有这个 .yml 文件:
section1:
key1: "value1"
key2: "value2"
section2:
key1: "value1"
key2: "value2"
Then define 2 Java POJOs:
然后定义 2 个 Java POJO:
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "section1")
public class MyCustomSection1 {
private String key1;
private String key2;
// define setters and getters.
}
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "section2")
public class MyCustomSection1 {
private String key1;
private String key2;
// define setters and getters.
}
Now you can autowire these beans in your component. For example:
现在您可以在组件中自动装配这些 bean。例如:
@Component
public class MyPropertiesAggregator {
@Autowired
private MyCustomSection1 section;
}
In case you are using Spring Boot everything will be auto scaned and instantiated:
如果您使用 Spring Boot,所有内容都将被自动扫描和实例化:
@SpringBootApplication
public class MainBootApplication {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(MainBootApplication.class)
.bannerMode(OFF)
.run(args);
}
}
If you'are using JUnit there is a basic test setup for loading YAML file:
如果您使用的是 JUnit,则有一个用于加载 YAML 文件的基本测试设置:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MainBootApplication.class)
public class MyJUnitTests {
...
}
If you're using TestNG there is a sample of test configuration:
如果您使用的是 TestNG,则有一个测试配置示例:
@SpringApplicationConfiguration(MainBootApplication.class)
public abstract class BaseITTest extends AbstractTestNGSpringContextTests {
....
}
回答by Mahmoud Eltayeb
`
`
package com.yaml.yamlsample;
import com.yaml.yamlsample.config.factory.YamlPropertySourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource(value = "classpath:My-Yaml-Example-File.yml", factory = YamlPropertySourceFactory.class)
public class YamlSampleApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(YamlSampleApplication.class, args);
}
@Value("${person.firstName}")
private String firstName;
@Override
public void run(String... args) throws Exception {
System.out.println("first Name :" + firstName);
}
}
package com.yaml.yamlsample.config.factory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.util.List;
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null) {
return super.createPropertySource(name, resource);
}
List<PropertySource<?>> propertySourceList = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
if (!propertySourceList.isEmpty()) {
return propertySourceList.iterator().next();
}
return super.createPropertySource(name, resource);
}
}
My-Yaml-Example-File.yml
My-Yaml-Example-File.yml
person:
firstName: Mahmoud
middleName:Ahmed
Reference my example on github spring-boot-yaml-sampleSo you can load yaml files and inject values using @Value()
参考我在 github spring-boot-yaml-sample 上的例子所以你可以加载 yaml 文件并使用 @Value() 注入值
回答by Atishay Jain
I spend 5 to 6 hours in understanding why external configuration of yml/yaml file(not application.yml) are so different.I read various articles, stack overflow questions but didn't get correct answer.
我花了 5 到 6 个小时来理解为什么 yml/yaml 文件(不是 application.yml)的外部配置如此不同。我阅读了各种文章,堆栈溢出问题,但没有得到正确答案。
I was stuck in between like I was able to use custom yml file value using YamlPropertySourceLoader but not able to use @Value because it is giving me error like Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'fullname.firstname' in value "${fullname.firstname}"
我被困在两者之间,就像我能够使用 YamlPropertySourceLoader 使用自定义 yml 文件值但无法使用 @Value 一样,因为它给了我错误,例如 自动装配依赖项的注入失败;嵌套异常是 java.lang.IllegalArgumentException:无法解析值“${fullname.firstname}”中的占位符“fullname.firstname”
fullname is a property in yml.
fullname 是 yml 中的一个属性。
Then I used "turtlesallthewaydown" given above solution, then at last I was able to use @Value without any issues for yaml files and I removed YamlPropertySourceLoader.
然后我使用了上述解决方案中给出的“turtlesallthewaydown”,最后我能够使用@Value 对 yaml 文件没有任何问题,并且我删除了 YamlPropertySourceLoader。
Now I understand the difference between YamlPropertySourceLoader and PropertySourcesPlaceholderConfigurer, a big thanks, however I have added these changes in my git repo.
现在我明白了 YamlPropertySourceLoader 和 PropertySourcesPlaceholderConfigurer 之间的区别,非常感谢,但是我已经在我的 git repo 中添加了这些更改。
Git Repo: https://github.com/Atishay007/spring-boot-with-restful-web-services
Git 仓库:https: //github.com/Atishay007/spring-boot-with-restful-web-services
Class Name: SpringMicroservicesApplication.java
类名:SpringMicroservicesApplication.java