我有一个Map< String,String>我想告诉Spring在创建bean和解析属性占位符时使用它.最简单的方法是什么?这是一个例子:
@Component
public class MyClass {
private String myValue;
@Autowired
public MyClass(@Value("${key.in.map}") String myValue) {
this.myValue = myValue;
}
public String getMyValue() {
return myValue;
}
}
public static void main(String[] args) {
Map
最佳答案
Spring提供了一个
MapPropertySource
,您可以在ApplicationContext的环境中注册(您需要一个大多数ApplicationContext实现提供的ConfigurableEnvironment).
解析器(按顺序)使用这些已注册的PropertySource值来查找占位符名称的值.
这是一个完整的例子:
@Configuration
@ComponentScan
public class Example {
@Bean
public static PropertySourcesPlaceholderConfigurer configurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
// can also add it here
//configurer.setPropertySources(propertySources);
return configurer;
}
public static void main(String[] args) {
MapfigApplicationContext ctx = new AnnotationConfigApplicationContext();
MapPropertySource propertySource = new MapPropertySource("map-source",propertyMap);
ctx.getEnvironment().getPropertySources().addLast(propertySource);
ctx.register(Example.class);
ctx.refresh();
MyClass instance = ctx.getBean(MyClass.class);
System.out.println(instance.getMyValue());
}
}
@Component
class MyClass {
private String myValue;
@Autowired
public MyClass(@Value("${key.in.map}") String myValue) {
this.myValue = myValue;
}
public String getMyValue() {
return myValue;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。