java 在一个spring boot项目中,如何将application.yaml加载到Java Properties中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43796664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In a spring boot project, how to load application.yaml into Java Properties
提问by Hollando Romi
If I have the following properties in application.yaml:
如果我在 application.yaml 中有以下属性:
myPro:
prop1: prop1value
prop2: prop2value
....
Is there a way to load this into a Java Properties
object?
有没有办法将它加载到 JavaProperties
对象中?
回答by g00glen00b
By default, Spring already puts all those application properties in its environment which is a wrapper of Properties
, for example:
默认情况下,Spring 已经将所有这些应用程序属性放在它的环境中,它是 的包装器Properties
,例如:
@Autowired
private Environment environment;
public void stuff() {
environment.getProperty("myPro.prop1");
environment.getProperty("myPro.prop2");
}
However, if you just want to use the values, you can always use the @Value
annotation, for example:
但是,如果您只想使用值,则始终可以使用@Value
注释,例如:
@Value("${myPro.prop1}")
private String prop1;
@Value("${myPro.prop2}")
private String prop2;
Lastly, if you really want a Properties
object with just everything in myPro
, you can create the following bean:
最后,如果你真的想要一个Properties
只有所有东西的对象myPro
,你可以创建以下 bean:
@ConfigurationProperties(prefix = "myPro")
@Bean
public Properties myProperties() {
return new Properties();
}
Now you can autowire the properties and use them:
现在您可以自动装配属性并使用它们:
@Autowired
@Qualifier("myProperties")
private Properties myProperties;
public void stuff() {
myProperties.getProperty("prop1");
myProperties.getProperty("prop2");
}
In this case, you don't necessarily have to bind it to Properties
, but you could use a custom POJO as well as long as it has a fieldname prop1
and another fieldname prop2
.
在这种情况下,您不必将其绑定到Properties
,但您可以使用自定义 POJO,只要它有一个 fieldnameprop1
和另一个 fieldname prop2
。
These three options are also listed in the documentation:
这三个选项也在文档中列出:
Property values can be injected directly into your beans using the
@Value
annotation, accessed via Spring'sEnvironment
abstraction or bound to structured objects via@ConfigurationProperties
.
属性值可以使用
@Value
注解直接注入到你的 bean 中,通过 Spring 的Environment
抽象访问或通过@ConfigurationProperties
.
回答by victorlage7
I solved my problem using the dependency on my pom.xml
我使用对我的依赖解决了我的问题 pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>