Announcement Announcement Module
Collapse
No announcement yet.
How to create multiple new instances of a bean? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to create multiple new instances of a bean?

    I am trying to work out how to instantiate multiple instances of the same bean. I can see many examples of using the ApplicationContext.getBean() methodology, but this is then frowned upon in the same documentation. I presume I need to do this with some sort of factory method but cannot find a good simple example to follow. See code below, can anyone help?

    Imagine this code. What would be the Spring implementation of the line with the new keyword?

    for( String customerId : List<String> Customers){
    CustomerEmailerImpl customer = new CustomerEmailerImpl(customer);
    customer.sendReminder();
    }

    Cheers
    Gene

  • #2
    Hi Gene,

    i do it this way with factory, create a prototype bean and if you need a new instance ask the factory for one, sorry for my bad english. Here is an example

    Configuration:
    Code:
    <bean id="myBean" class="com.foo.bar.MyBean" scope="prototype"/>
    		  
    <bean id="myBeanFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
      <property name="targetBeanName">
        <idref local="myBean"/>
      </property>
    </bean>
    Then autowire the factory in your service:
    Code:
    @Autowired
    private ObjectFactory<MyBean> myBeanFactory;
    To get a new instance of your prototype MyBean do:
    Code:
    MyBean  myNewBean = myBeanFactory.getObject();
    Hope it helps

    Comment


    • #3
      I am using annotation based configuration is this a good solution?

      Using my original example is this how you would do it in annotation based configuration?

      CustomerEmailerImpl:
      Code:
      @Scope("prototype")
      public class CustomerEmailerImpl{
        ... Do something here
      }
      Then in code which needs to create multiple instances
      Code:
      @Autowired private ObjectFactory<CustomerEmailerImpl> customerEmailerImplFactory;
      
      public void sendReminders(){
      //Assume Customers is already set for( String customerId : List<String> Customers){ CustomerEmailerImpl customer = customerEmailerImplFactory.getObject(); //Change code so runtime attributes are set in a different area of the code customer.init(customerId) customer.sendReminder(); }
      }

      Comment

      Working...
      X