由于您正在使用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 {
@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);
}
private Properties load(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException ex) {
Throwable cause = ex.getCause();
if (cause instanceof FileNotFoundException) throw (FileNotFoundException) cause;
throw ex;
}
}
}
当你使用以下方式时,你需要告诉 @PropertySource
注释要使用这个工厂而不是默认的工厂;
@Component
@PropertySource(value = "classpath:config-prop.yml", factory = YamlPropertySourceFactory.class)
public class ResourceProvider {
@Value("${app.max.size}")
private int size;
}
您可以使用上面代码片段中显示的属性的size
变量。
但是,如果您正在使用YAML数组声明来获取属性,则即使使用此方式也会有些奇怪。
yaml
文件。 - Darren Forsythe