首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Spring Framework4.1中使用YamlPropertiesFactoryBean加载YAML文件?

如何在Spring Framework4.1中使用YamlPropertiesFactoryBean加载YAML文件?
EN

Stack Overflow用户
提问于 2015-02-04 00:20:26
回答 4查看 80.6K关注 0票数 42

我有一个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,比如this one

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-03-03 18:42:40

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

当然,您必须在运行时类路径上具有snakeyaml依赖项。

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

编辑:

为了完整起见,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;
}
票数 75
EN

Stack Overflow用户

发布于 2018-10-20 02:54:21

`

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

person:
  firstName: Mahmoud
  middleName:Ahmed

在github上引用我的示例,这样您就可以使用@ spring-boot-yaml-sample ()加载yaml文件并注入值。

票数 5
EN

Stack Overflow用户

发布于 2016-05-17 16:22:38

要在Spring中读取.yml文件,可以使用next方法。

例如,您具有以下.yml文件:

section1:
  key1: "value1"
  key2: "value2"
section2:
  key1: "value1"
  key2: "value2"

然后定义两个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.
}

现在,您可以在组件中自动连接这些bean。例如:

@Component
public class MyPropertiesAggregator {

    @Autowired
    private MyCustomSection1 section;
}

如果你使用的是Spring Boot,所有的东西都会被自动扫描和实例化:

@SpringBootApplication
public class MainBootApplication {
     public static void main(String[] args) {
        new SpringApplicationBuilder()
            .sources(MainBootApplication.class)
            .bannerMode(OFF)
            .run(args);
     }
}

如果你使用的是JUnit,有一个基本的测试设置来加载YAML文件:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MainBootApplication.class)
public class MyJUnitTests {
    ...
}

如果您使用的是TestNG,这里有一个测试配置示例:

@SpringApplicationConfiguration(MainBootApplication.class)
public abstract class BaseITTest extends AbstractTestNGSpringContextTests {
    ....
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28303758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档