小编典典

如何使用YamlPropertiesFactoryBean使用Spring Framework 4.1加载YAML文件?

spring

我有一个spring应用程序,当前正在使用* .properties文件,而我想使用YAML文件代替它。

我发现类YamlPropertiesFactoryBean似乎能够满足我的需要。

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

以前,我使用@PropertySource加载属性文件,如下所示:

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

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

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

谢谢。

我的应用程序使用基于注释的配置,而我使用的是Spring Framework 4.1.4。我找到了一些信息,但它总是使我像上面这样指向Spring Boot 。


阅读 1486

收藏
2020-04-12

共1个答案

小编典典

使用XML config,我一直在使用这种结构:

<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依赖性。

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

编辑:

java config为完整性起见

@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;
}
2020-04-12