[英]How to inject a Map in Spring @Value field?
如何將以下application.properties
注入Map
字段?
my.server.url=localhost
my.server.port=8080
my.server.timeout=10000
下面的課有什么問題?
@Service
@ConfigurationProperties("my")
public class MyService {
private Map<String, String> server;
public void setServer(Map<String, String> server) { this.server = server; }
public MyService(WebClient.Builder builder) {
this.builder = builder.uri(server.get("url")).build();
}
}
結果:
通過構造函數實例化 Bean 失敗; 嵌套異常是 org.springframework.beans.BeanInstantiationException:無法實例化 [MyService]:構造函數拋出異常; 嵌套異常是 java.lang.NullPointerException
在配置類中創建一個 bean,如下所示:
@Bean(name = "appProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("application.properties"));
return bean;
}
然后將其中的值作為映射注入到所需的類中,如下所示:
@Resource(name = "appProperties")
private Map<String, String> properties;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.