java - 使用 SpEL 表达式和 PropertyPlaceHolder 设置 Spring bean 类名

标签 java spring

更新:截至 2016 年 12 月 9 日的决议摘要

根据下面@altazar 的回答,this is now possible从 Spring 4.2 开始!

截至 2012 年 3 月 29 日的旧决议摘要

截至目前,Spring SpEL 无法在 class 中执行 <bean> 的属性.

原始问题:

我正在尝试实现动态 class Spring bean 的属性,最终使用 PropertyPlaceHolder 的组合设置属性和 SpEL 表达式。目的是选择要实例化的类的生产版本或调试版本。它不起作用,我想知道是否有可能实现。

到目前为止,我有以下内容:

平面属性文件:

is.debug.mode=false

Spring XML 配置:

<bean id="example"
      class="#{ ${is.debug.mode} ?
                    com.springtest.ExampleDebug :
                    com.springtest.ExampleProd}"
/>

Spring bootstrap 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 执行此操作。我还意识到我正在使用基于文件系统的上下文和路径 - 我也有理由这样做。

最佳答案

您可以使用 factoryBean 完成您想要的:

<bean id="example" class="MyFactoryBean">
  <property name="class" value="#{ ${is.debug.mode} ? com.springtest.ExampleDebug : com.springtest.ExampleProd}"/>
</bean>

其中 MyFactoryBean 是返回指定类实例的普通 FactoryBean 实现。

关于java - 使用 SpEL 表达式和 PropertyPlaceHolder 设置 Spring bean 类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9907845/

相关文章:

java - 如何配置 JUnit 仅在测试方法中忽略 @Before 注释

java - 在Java中生成2个给定日期之间的所有日期

java - 前端或后端的 api 错误消息的国际化?

java - Spring Jackson 通过 Id 引用现有对象反序列化对象

java |验证包装器内的 JSON 对象

c# - 使用 JAVA 访问动态 AX 方法

java - 从 cmd 编译 java 程序时,我得到 "error: cannot find symbol",但在 Eclipse 中却没有

java - 为什么以下异常专门显示 -4 索引而不是 -1?

spring - java.lang.NoSuchMethodError :org. apache.cxf.service.model.MessageInfo.getFirstMessagePart() org/apache/cxf/service/model/MessagePartInfo;

java - gradle:将 spring 应用程序迁移到多项目构建