Spring Boot-从属性文件注入映射 [英] Spring Boot - inject map from properties file
问题描述
属性文件如下:
url1=path_to_binary1
url2=path_to_binary2
根据此,我尝试了以下方法:
According this I tried following approach:
@Component
@EnableConfigurationProperties
public class ApplicationProperties {
private Map<String, String> pathMapper;
//get and set
}
,在另一个组件中,我自动连接了ApplicationProperties:
and in another component I autowired ApplicationProperties:
@Autowired
private ApplicationProperties properties;
//inside some method:
properties.getPathMapper().get(appName);
产生NullPointerException
.
如何更正?
我有正确的user7757360建议:
I have correct according user7757360 advice:
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
和属性文件:
app.url1=path_to_binary1
app.url2=path_to_binary2
仍然无法正常工作
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
private Map<String, String> app;
和application.properties
内部:
app.url1=path_to_binary1
app.url2=path_to_binary2
仍然无法正常工作
推荐答案
NullPointerException
可能来自空的ApplicationProperties
.
所有自定义属性都应带有注释@ConfigurationProperties(prefix="custom")
.
之后,必须在主类(具有主方法的类)上添加@EnableConfigurationProperties(CustomProperties.class)
.
对于自动完成功能,您可以使用:
All custom properties should be annotated @ConfigurationProperties(prefix="custom")
.
After that, on your main class (class with main method) you must add @EnableConfigurationProperties(CustomProperties.class)
.
For autocomplete you can use:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
如果使用不带前缀的@ConfigurationProperties
,则仅使用字段名称.您的属性中的字段名称.对于您的情况path-mapper
,接下来要指定key
和value
.示例:
If you use @ConfigurationProperties
without prefix you use only field name. Field name in you properites. In your case path-mapper
, next you specific key
and value
. Example:
path-mapper.key=value
在更改自己的属性后,请重新加载应用程序.示例:
Remeber after changes in your own properites you need to reload application. Example:
https://github.com/kchrusciel/SpringPropertiesExample
这篇关于Spring Boot-从属性文件注入映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!