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

查看:39
本文介绍了如何使用 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.

我更喜欢 XML 配置而不是 Java 配置,但我认为转换它应该不难.

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


为了完整起见,java配置

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天全站免登陆