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

nqwrtyyt  于 2023-05-05  发布在  Java
关注(0)|答案(3)|浏览(303)

我有一个项目,但不是在spring,我如何使用annotation来读取资源包下的配置文件中的内容,如*.yaml or *.properties

w41d8nur

w41d8nur1#

您可以在没有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 ); });

Reference.

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

假设你有一个application.properties,位于src/main/resources中,其中有一个条目application.name="My Spring Boot Application",那么在你的一个类中用@Component或它的任何子原型注解注解,可以像这样获取值:

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

www.example.com文件中的属性application.property现在绑定到此变量applicationName
您也可以有一个application.yml文件,并以这种方式编写相同的属性

application:
  name: "My Spring Boot Application"

您将以与上次相同的方式获得此属性值,方法是使用@Value注解a字段。

cunj1qz1

cunj1qz12#

yaml中的平面属性

import static java.lang.String.format;
import static java.lang.System.getenv;
import static java.util.Collections.singletonMap;
import static org.apache.commons.lang3.StringUtils.isBlank;

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) {
        Yaml yaml = new Yaml();
        Properties properties = new Properties();
        properties.putAll(getFlattenedMap(yaml.load(PropertiesUtils.class.getClassLoader().getResourceAsStream("application.yml"))));
        if (profile != null)
            properties.putAll(getFlattenedMap(yaml.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(format("application-$s.yml", profile)))));
        System.out.println(properties);
        return properties;
    }

    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 : "");
            }
        });
    }
}
e3bfsja2

e3bfsja23#

我理解你的问题是关于使用.yaml和.properties文件访问内容***而不使用Spring框架,***但是***如果你可以在classpath中访问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");

相关问题