如何使用YamlPropertiesFactoryBean使用Spring Framework 4.1加载YAML文件? [英] How to use YamlPropertiesFactoryBean to load YAML files using Spring Framework 4.1?

查看:227
本文介绍了如何使用YamlPropertiesFactoryBean使用Spring Framework 4.1加载YAML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个当前正在使用* .properties文件的spring应用程序,我希望使用YAML文件。

I have a spring application that is currently using *.properties files and I want to have it using YAML files instead.

我发现类YamlPropertiesFactoryBean 似乎能够做我做的事情需要。

I found the class YamlPropertiesFactoryBean that seems to be capable of doing what I need.

我的问题是我不确定如何在我的Spring应用程序中使用此类(使用基于注释的配置)。
我似乎应该在中配置它PropertySourcesPlaceholderConfigurer 包含 setBeanFactory 方法。

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 PropertySourcesPlaceholderConfigurer with the setBeanFactory method.

以前我使用@PropertySource 如下:

@Configuration
@PropertySource("classpath:/default.properties")
public class PropertiesConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

如何在PropertySourcesPlaceholderConfigurer中启用YamlPropertiesFactoryBean,以便我可以直接加载YAML文件吗?
或者还有另一种方法吗?

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?

谢谢。

我的应用程序正在使用注释基于配置,我正在使用Spring Framework 4.1.4。
我找到了一些信息,但它始终指向Spring Boot,就像这个

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.

推荐答案

使用XML配置我一直在使用这个结构:

With XML config I've been using this construct:

<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"/>

当然,你必须对你的运行时类路径有一个snakeyaml依赖。

Of course you have to have the snakeyaml dependency on your runtime classpath.

我比java配置更喜欢XML配置,但我认为它不应该很难转换它。

I prefer XML config over the java config, but I recon it shouldn't be hard to convert it.

编辑:

java config为完整起见

edit:
java config for completeness sake

@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;
}

这篇关于如何使用YamlPropertiesFactoryBean使用Spring Framework 4.1加载YAML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆