Spring boot spring引导从yml文件读取属性

Spring boot spring引导从yml文件读取属性,spring-boot,Spring Boot,我有一个spring引导应用程序,其中属性必须从yaml文件中读取 代码: yaml文件 app: max: size: 10 当我尝试这个时,它不起作用。我将app.max.size的值设置为null。对于size我得到的值为10 当我使用application.properties时。我能得到想要的结果。 我做错什么了吗 应用程序属性 app.max.size=10 您可以通过以下方式读取该值: @Value("${app.max.size}") private Strin

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

代码:

yaml文件

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

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

应用程序属性

 app.max.size=10

您可以通过以下方式读取该值:

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

public String getValue(String key) {
   return size;
}

从文件中:

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


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

@Value("${app.max.size}")
private int size;
@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;
}
如果您是laoding custom
YAML
文件,那么这在春季仍然是一个巨大的问题。使用
@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;
        }
    }
}
您可以使用上面代码段的
size
变量中显示的属性


不过。如果您使用YAML数组声明来获取属性,那么即使您使用这种方式,也不会有什么特别之处。

我有多个属性,不想为此定义变量。可以添加新属性,但不想更改此文件。对于yml文件,它也可以工作。检查你的档案。是yml还是yaml?@PropertySource(“classpath:application.yml”)typo@sajib,我已尝试使用.yml和.yaml,但仍然为空。如果我尝试
app
,结果是空字符串。@dassum,键入的是什么?如果有输入错误,如何获取
size
的值?请阅读Spring Boot文档。根据正确的约定,它将自动读取
yaml
文件。谢谢您的回答。我想我得用这个。但是我在寻找一些我不必实现
PropertySourceFactory
@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;
}