java - Spring IoC : Conditional Injection in run time

标签 java spring oop design-patterns spring-ioc

如何使用框架有条件地从外部注入(inject) Bean(不创建工厂类)?

在下面的场景中,两个 childBean 都已经实例化,但在运行时根据条件注入(inject)到父 Bean 中。

<bean id=ChildBean1>
<bean id=ChildBean2>
<parentBean name='parentBean' lazy-init="true">
   <property name='flag'>

   <somecondition flag=1/>  
   <property name='child' ref ='childBean1'/>
   <somecondition flag=2/> 
   <property name='child' ref ='childBean2'/>
</parentBean>

最佳答案

您可以通过 spring 表达式语言(SpEL)来完成:

<bean class="com.example.spring.TestBean">
    <property name="dependency" value="#{systemProperties['profile'] == 'test' ? dependencyA : dependencyB}" />
</bean>

也可以使用如下所示的 Java 配置:

@Bean
public HelloBean helloBean() {
    HelloBean helloBean = new HelloBean ();
    if (condition) {
        helloBean.setDependency(dependencyA());
    } else {
        helloBean.setDependency(dependencyB());
    }
    return helloBean;
}

关于java - Spring IoC : Conditional Injection in run time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427165/

相关文章:

java - jersey-spring 和 jenkins - 读取 zip 文件/jersey-core-1.8.jar 时出现奇怪错误

java - Spring Batch 和 Spring 集成。无法配置JobListener

c++ - cv::Mat 类是否存在设计缺陷?

php - 如何将旧的 OOP PHP 项目转换为 Yii 框架?

java - 设置字段与创建新对象

java - 是否可以在 JPA 中映射 map<String,List<Entity>>?

java - 在构建器类范例中处理空值等?

Java Jsoup Google 图片搜索结果解析

java - 使用 selenium 在 java 中使用 testng 进行并行测试

java - 如何让 Spring WebServices 记录所有 SOAP 请求?