java+解析占位符,如何告诉Spring使用Java映射来解析属性占位符?
Spring提供了一個(gè)
MapPropertySource,您可以在ApplicationContext的環(huán)境中注冊(cè)(您需要一個(gè)大多數(shù)ApplicationContext實(shí)現(xiàn)提供的ConfigurableEnvironment).
解析器(按順序)使用這些已注冊(cè)的PropertySource值來查找占位符名稱的值.
這是一個(gè)完整的例子:
@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) {
Map propertyMap = new HashMap<>();
propertyMap.put("key.in.map", "value.in.map");
AnnotationConfigApplicationContext 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;
}
}
總結(jié)
以上是生活随笔為你收集整理的java+解析占位符,如何告诉Spring使用Java映射来解析属性占位符?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php_sapi常量,PHP常量PHP_
- 下一篇: 2013年3月编程语言排行榜:有毒的Ja