gpt4 book ai didi

java - Spring Boot - 从属性文件注入(inject)映射

转载 作者:行者123 更新时间:2023-12-03 22:00:30 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to fill HashMap from java property file with Spring @Value

(8 个回答)


1年前关闭。




属性文件如下所示:

url1=path_to_binary1
url2=path_to_binary2

根据 this我尝试了以下方法:
@Component
@EnableConfigurationProperties
public class ApplicationProperties {
private Map<String, String> pathMapper;

//get and set
}

在另一个组件中,我 Autowiring 了 ApplicationProperties:
@Autowired
private ApplicationProperties properties;
//inside some method:
properties.getPathMapper().get(appName);

生产 NullPointerException .

如何纠正它?

更新

根据 user7757360 的建议,我有正确的建议:
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {

和属性文件:
app.url1=path_to_binary1
app.url2=path_to_binary2

还是不行

更新 2
@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

还是不行

最佳答案

如果您可以为属性文件提供更具体的示例,将会很有帮助。您应该在 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
}

更多信息请访问 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml

关于java - Spring Boot - 从属性文件注入(inject)映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43098009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com