Spring可变数量的实例

时间:2011-07-27 06:25:54

标签: java spring dependency-injection runtime

我现在进入Spring,我有一个问题。假设我们有一个接口IControl,我们有三个实现 - 例如ButtonLabelCheckbox。 用户将在运行时输入数字N,我应该创建特定类型的N控件(ButtonLabelCheckbox)。问题是我希望在程序运行之前配置此特定类型。例如,我在我的spring.xml中配置了我想要的按钮,然后程序运行,用户输入10并创建10按钮。

<beans>
   <bean id="controlCreator" class="org.company.ControlCreator">
       <property name="controlType" ref="?!?!?!?!?!?!"/>
   </bean>   
</beans>

我该如何配置?

P.S这只是我编写的一个学习例子。

祝你好运, 斯托

2 个答案:

答案 0 :(得分:4)

首先,请允许我声明Spring并不打算这样做。 Spring希望采用一种不引人注意的方法将组件连接在一起。它并不意味着在运行时用于生成对象。

正确的方法

正确的方法是设计工厂类。您可以在启动时使用Spring设置默认值,然后在运行时向工厂询问实例。

侵入式apporach

如果你真的想使用Spring,你可以通过向applicationContext询问你的控件实例来进行干扰。

默认情况下,所有Spring bean都是单例,但您可以将它们变成原型。

免责声明:代码未经过测试,但应该是这样的:

<强>的applicationContext.xml

<beans>
   <bean id="myButton" class="org.company.Control" scope="prototype">
       <property name="controlType" value="button" />
   </bean>   

   <bean id="controlCreator" class="org.company.ControlCreator" scope="singleton">
   </bean>   

</beans>

<强>代码

public class controlCreator implements ApplicationContextAware {

  private ApplicationContext appContext;

  public Control createButton(){
    // since this bean is prototype, a new one will be created like this
    return getApplicationContext().getBean("myButton");
  }


  // ... getter and setter for applicationContext

}

非侵入式方法

如果你真的想要使用Spring,并且你真的想要无拘无束地使用它,你将不得不使用 Method Injection 。在您的班级中注入工厂方法。

代码如下:

<强>的applicationContext.xml

<beans>
   <bean id="myButton" class="org.company.Control" scope="prototype">
       <property name="controlType" value="button" />
   </bean>   

   <bean id="controlCreator" class="org.company.ControlCreator" scope="singleton">
       <lookup-method bean="myButton" name="createButton"/>
   </bean>   

</beans>

<强>代码

public class controlCreator implements ApplicationContextAware {

  private ApplicationContext appContext;

  public abstract Control createButton();


  // ... getter and setter for applicationContext

}

这将在调用lookup方法时返回bean。由于bean是原型,它将创建一个新的。

答案 1 :(得分:1)

你不能创建相同spring bean的N个实例,因为bean是单例,ref应该引用这个bean单例。

你可以做的是使controlCreator抽象,然后配置不同的实现,创建不同的控件。

相关问题