【发布时间】:2012-03-28 12:48:14
【问题描述】:
更新:截至 2016 年 12 月 9 日的决议摘要
根据下面@altazar 的回答,this is now possible 从 Spring 4.2 开始!
截至 2012 年 3 月 29 日的旧决议摘要
截至目前,Spring SpEL 无法在class 的class 属性内执行<bean>。
原问题:
我正在尝试为 Spring bean 实现动态 class 属性,最终使用 PropertyPlaceHolder 属性和 SpEL 表达式的组合进行设置。目的是选择要实例化的类的生产版本或调试版本。它不起作用,我想知道是否有可能实现。
到目前为止,我有以下内容:
平面属性文件:
is.debug.mode=false
Spring XML 配置:
<bean id="example"
class="#{ ${is.debug.mode} ?
com.springtest.ExampleDebug :
com.springtest.ExampleProd}"
/>
Spring 引导 Java 代码:
// Get basic ApplicationContext - DO NOT REFRESH
FileSystemXmlApplicationContext applicationContext = new
FileSystemXmlApplicationContext
(new String[] {pathSpringConfig}, false);
// Load properties
ResourceLoader resourceLoader = new DefaultResourceLoader ();
Resource resource = resourceLoader.getResource("file:" + pathProperties);
Properties properties = new Properties();
properties.load(resource.getInputStream());
// Link to ApplicationContext
PropertyPlaceholderConfigurer propertyConfigurer =
new PropertyPlaceholderConfigurer() ;
propertyConfigurer.setProperties(properties) ;
applicationContext.addBeanFactoryPostProcessor(propertyConfigurer);
// Refresh - load beans
applicationContext.refresh();
// Done
Example example = (Example) applicationContext.getBean("example");
错误消息(为清楚起见删除了很多空格):
Caused by: java.lang.ClassNotFoundException:
#{ true ? com.springtest.ExampleDebug : com.springtest.ExampleProd}
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
. . .
从消息中的“true”可以看出,is.debug.mode 属性已成功加载和替换。但还有其他事情出错了。它是我在 Java 中的引导序列吗?还是 XML 中的 SPeL 语法?还是其他问题?
顺便说一句,我知道新的 3.1 配置文件功能,但出于各种原因,我想通过 SPeL 执行此操作。我也意识到我正在使用基于文件系统的上下文和路径 - 我也有理由这样做。
【问题讨论】: