Spring Boot-从属性文件注入映射 [英] Spring Boot - inject map from properties file

查看:112
本文介绍了Spring Boot-从属性文件注入映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

属性文件如下:

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,接下来要指定keyvalue.示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆