如何在没有Spring框架的情况下读取配置文件(*.yaml *.properties)

问题描述 投票:0回答:3

我有一个项目,但不是spring的,如何使用注解读取资源包下

*.yaml or *.properties
等配置文件中的内容。

java annotations config
3个回答
18
投票

您可以在没有 Spring 的情况下使用 SnakeYAML。

下载依赖:

compile group: 'org.yaml', name: 'snakeyaml', version: '1.24'

然后你可以这样加载.yaml(或.yml)文件:

Yaml yaml = new Yaml();
InputStream inputStream = this.getClass().getClassLoader()
                           .getResourceAsStream("youryamlfile.yaml"); //This assumes that youryamlfile.yaml is on the classpath
Map<String, Object> obj = yaml.load(inputStream);
obj.forEach((key,value) -> { System.out.println("key: " + key + " value: " + value ); });

参考。

编辑:经过进一步调查,OP想知道如何在Spring boot中加载属性。 Spring Boot 有一个内置的读取属性的功能。

假设您有一个 application.properties 位于 src/main/resources 中,其中有一个条目为

application.name="My Spring Boot Application"
,然后在用
@Component
或其任何子原型注释注释的类之一中,有一个可以获取这样的值:

@Value("${application.name}")
private String applicationName;

application.property 文件中的属性现在已绑定到此变量

applicationName

您还可以有一个 application.yml 文件并以这种方式编写相同的属性

application:
  name: "My Spring Boot Application"

您将像上次一样通过使用

@Value
注释对字段进行注释来获取此属性值。


2
投票

我理解您的问题是关于使用 .yaml 和 .properties 文件访问内容,没有使用 Spring 框架,但是如果您确实可以在类路径中访问 Spring 框架并且不介意使用一些内部类,下面的代码可以非常简洁的读取内容

对于属性文件:

    File file = ResourceUtils.getFile("classpath:application.properties");
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new PathResource(file.toPath()));
    propertiesFactoryBean.afterPropertiesSet();

    // you now have properties corresponding to contents in the application.properties file in a java.util.Properties object
    Properties applicationProperties = propertiesFactoryBean.getObject();   
    // now get access to whatever property exists in your file, for example
    String applicationName = applicationProperties.getProperty("spring.application.name"); 

对于 Yaml 资源

    File file = ResourceUtils.getFile("classpath:application.yaml");
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new PathResource(file.toPath()));
    factory.afterPropertiesSet();

    // you now have properties corresponding to contents in the application.yaml file in a java.util.Properties object
    Properties applicationProperties = factory.getObject();
    // now get access to whatever property exists in your file, for example
    String applicationName = applicationProperties.getProperty("spring.application.name"); 

2
投票

来自 yaml 的扁平属性

import static java.lang.String.format;
import static java.lang.System.getenv;
import static java.nio.charset.Charset.defaultCharset;
import static java.util.Collections.singletonMap;
import static org.apache.commons.io.IOUtils.resourceToString;
import static org.apache.commons.lang3.StringUtils.isBlank;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import org.yaml.snakeyaml.Yaml;

public class PropertiesUtils {

    public static Properties loadProperties() {
        return loadProperties(getenv("ENV"));
    }

    public static Properties loadProperties(String profile) {
        try {
            Yaml yaml = new Yaml();
            Properties properties = new Properties();
            properties.putAll(getFlattenedMap(yaml.load(resourceToString("/application-config.yml", defaultCharset()))));
            if (profile != null)
                properties.putAll(getFlattenedMap(yaml.load(resourceToString(format("/application-config-%s.yml", profile), defaultCharset()))));
            return properties;
        } catch (IOException e) {
            throw new Error("Cannot load properties", e);
        }
    }

    private static final Map<String, Object> getFlattenedMap(Map<String, Object> source) {
        Map<String, Object> result = new LinkedHashMap<>();
        buildFlattenedMap(result, source, null);
        return result;
    }

    @SuppressWarnings("unchecked")
    private static void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, String path) {
        source.forEach((key, value) -> {
            if (!isBlank(path))
                key = path + (key.startsWith("[") ? key : '.' + key);
            if (value instanceof String) {
                result.put(key, value);
            } else if (value instanceof Map) {
                buildFlattenedMap(result, (Map<String, Object>) value, key);
            } else if (value instanceof Collection) {
                int count = 0;
                for (Object object : (Collection<?>) value)
                    buildFlattenedMap(result, singletonMap("[" + (count++) + "]", object), key);
            } else {
                result.put(key, value != null ? "" + value : "");
            }
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.