我前一阵子有同样的问题,这是我做这个工作的方式:
首先,当你自举你的Spring应用程序上下文(我用基于注解的配置,但同样要基于XML工作) ,你必须添加一个自定义的PropertySource,这是Spring支持添加新的解析属性的方式。事情是这样的:
public static void initialize() {
ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().getPropertySources().addFirst(new PlayFrameworkPropertySource());
ctx.scan("somepackage");
ctx.refresh();
}
自定义类PlayFrameworkPropertySource
是确实的魔力之一:
public class PlayFrameworkPropertySource extends PropertySource<Object> {
public PlayFrameworkPropertySource() {
super("Play Framework properties resolution mechanism");
}
@Override
public Object getProperty(String propertyName) {
// or ConfigFactory.load().getString(propertyName), as you prefer...
return Configuration.root().getString(propertyName);
}
}
为了让这一切的工作,你只需要做一件事:明确声明PropertySourcesPlaceholderConfigurer类型的一些@Configuration类豆你可能会使用:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
重要提示:该豆必须是static
,因为它是BeanFactoryPostProcessor,它应该在任何其他常规@Bean之前加载。
这对我来说就像一个魅力,希望这对别人有帮助!
干杯,
乔纳森
感谢。它为我做了诡计! – Khaleesi 2014-10-13 01:04:09