Spring Boot-从属性文件注入映射

gst*_*low 2 java configuration spring spring-boot

属性文件如下所示:

url1=path_to_binary1
url2=path_to_binary2
Run Code Online (Sandbox Code Playgroud)

根据这个我尝试以下方法:

@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}
Run Code Online (Sandbox Code Playgroud)

在另一个组件中,我自动连接了ApplicationProperties:

@Autowired
private ApplicationProperties properties;         
      //inside some method:
      properties.getPathMapper().get(appName);
Run Code Online (Sandbox Code Playgroud)

产生NullPointerException

如何纠正?

更新

我有正确的根据user7757360的建议:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
Run Code Online (Sandbox Code Playgroud)

和属性文件:

app.url1=path_to_binary1
app.url2=path_to_binary2
Run Code Online (Sandbox Code Playgroud)

仍然不起作用

更新2

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;
Run Code Online (Sandbox Code Playgroud)

里面application.properties

app.url1=path_to_binary1
app.url2=path_to_binary2
Run Code Online (Sandbox Code Playgroud)

仍然不起作用

lrv*_*lrv 5

如果您可以为属性文件提供更具体的示例,这将很有帮助。您应该在url1和url2中使用相同的前缀,然后才能使用

@ConfigurationProperties(prefix="my")

my.pathMapper.url1=path_to_binary1 my.pathMapper.url2=path_to_binary2

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="my")
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set for pathMapper are important
}
Run Code Online (Sandbox Code Playgroud)

详情请参阅https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml


kch*_*iel 3

NullPointerException大概是从空ApplicationProperties

所有自定义属性都应该被注释@ConfigurationProperties(prefix="custom")。之后,在您的主类(具有 main 方法的类)上,您必须添加@EnableConfigurationProperties(CustomProperties.class). 对于自动完成,您可以使用:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
Run Code Online (Sandbox Code Playgroud)

如果不使用@ConfigurationProperties前缀,则仅使用字段名称。您属性中的字段名称。根据您的情况path-mapper,接下来您将具体说明keyvalue。例子:

path-mapper.key=value
Run Code Online (Sandbox Code Playgroud)

请记住,在更改您自己的属性后,您需要重新加载应用程序。例子:

https://github.com/kchrusciel/SpringPropertiesExample