spring boot 从 yml 文件读取属性 [英] spring boot read properties from yml file

查看:55
本文介绍了spring boot 从 yml 文件读取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 spring boot 应用程序,其中的属性必须从 yaml 文件中读取.

I have a spring boot application where properties have to be read from a yaml file.

代码:

@Component
@PropertySource("classpath:application.yml")
public class ResourceProvider {

    @Autowire
    private Environment env;

    public String getValue(String key) {
        return env.getProperty("app.max.size");
    }
}

yaml 文件

app:
  max:
    size: 10

当我尝试这个时它不起作用.我将 app.max.size 的值设为 null.对于 size,我得到的值为 10.

When I try this it doesn't work. I get value for app.max.size as null. For size I get the value as 10.

当我使用 application.properties 时.我能够得到想要的结果.我做错了什么吗?

When I use application.properties. I am able to get the desired result. Am I doing anything incorrectly?

application.properties

application.properties

 app.max.size=10

推荐答案

由于您使用的是 application.yml 文件,因此您无需手动将文件加载到上下文中,因为它是spring 应用程序的默认配置文件.您可以简单地在 @Component 装饰类中使用它们,如下所示;

Since you'r using application.yml file, you don't need to manually load the file to the context as it's the default config file for spring application. You can simply use them in a @Component decorated class like below;

@Value("${app.max.size}")
private int size;

如果你正在加载自定义的 YAML 文件,那么这在 Spring 中仍然是一个大问题.使用 @PropertySource 你不能简单地加载 YAML 文件.这是可能的,但所需的工作很少.首先,您需要一个自定义属性源工厂.在您的情况下,自定义 YAML 属性源工厂.

If you're laoding custom YAML file, then this is a huge problem in Spring yet. Using @PropertySource you can't load YAML files simply. It's possible, but little work required. First you need a custom property source factory. In your case, custom YAML property source factory.

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    /**
     * Create a {@link PropertySource} that wraps the given resource.
     *
     * @param name     the name of the property source
     * @param resource the resource (potentially encoded) to wrap
     * @return the new {@link PropertySource} (never {@code null})
     * @throws IOException if resource resolution failed
     */
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {
        Properties properties = load(resource);
        return new PropertiesPropertySource(name != null ? name :
                Objects.requireNonNull(resource.getResource().getFilename(), "Some error message"),
                properties);
    }

    /**
     * Load properties from the YAML file.
     *
     * @param resource Instance of {@link EncodedResource}
     * @return instance of properties
     */
    private Properties load(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();

            return factory.getObject();
        } catch (IllegalStateException ex) {
            /*
             * Ignore resource not found.
             */
            Throwable cause = ex.getCause();
            if (cause instanceof FileNotFoundException) throw (FileNotFoundException) cause;
            throw ex;
        }
    }
}

而且,你需要告诉 @PropertySource 注释使用这个工厂而不是默认的,每当你像下面这样使用它时;

And, you need to tell @PropertySource annotation use this factory instead of default one whenever you use it like below;

@Component
@PropertySource(value = "classpath:config-prop.yml", factory = YamlPropertySourceFactory.class) // Note the file name with the extension unlike a property file. Also, it's not the `application.yml` file.
public class ResourceProvider { 

    @Value("${app.max.size}")
    private int size;
}

您可以使用上面代码片段的 size 变量中显示的属性.

You can use your properties shown in above code snippet's size variable.

虽然.如果您使用 YAML 数组声明来获取属性,即使您使用这种方式也没什么奇怪的.

Though. If you're using a YAML array declaration to get properties, that would be little peculiar even if you use this way.

这篇关于spring boot 从 yml 文件读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆