[英]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.