spring boot 从 yml 文件中读取属性

新手上路,请多包涵

我有一个 Spring Boot 应用程序,必须从 yaml 文件中读取属性。

代码:

 @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 的值设为空。对于 size 我得到的值为 10。

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

应用程序属性

 app.max.size=10

原文由 warrior107 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 675
2 个回答

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

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

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

 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 注释使用此工厂而不是默认工厂,无论何时使用它,如下所示;

 @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 变量中显示的属性。

尽管。如果您使用 YAML 数组声明来获取属性,即使您使用这种方式,这也有点奇怪。

原文由 Sachith Dickwella 发布,翻译遵循 CC BY-SA 4.0 许可协议

从文档中:

无法使用 @PropertySource 注解加载 YAML 文件。因此,如果您需要以这种方式加载值,则需要使用属性文件。

Spring Boot 官方文档参考

原文由 Toerktumlare 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进