【问题标题】:Spring IoC: Conditional Injection in run timeSpring IoC:运行时的条件注入
【发布时间】:2016-05-25 03:14:12
【问题描述】:

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

在下面的场景中,两个childBeans都将被实例化,但在运行时根据条件注入到父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>

【问题讨论】:

  • 查找和使用配置文件。

标签: java spring oop design-patterns spring-ioc


【解决方案1】:

你可以通过spring表达式语言(SpEL)来实现:

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

也可以使用类似下面的 Java Config:

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

【讨论】:

  • 嗨,谢谢,但我的要求是基于该事务的流动态地为每个事务注入依赖项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
  • 2016-08-17
  • 2010-11-29
相关资源
最近更新 更多