Announcement Announcement Module
No announcement yet.
Trouble getting non-singleton beans. Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Trouble getting non-singleton beans.

    Hello All,

    I'm not sure if it's just gotten too late at night and I can't think straight, but I'm having a problem getting non-singleton beans from the IoC container.

    I'm still in the testing phase of my Spring learning, but I'm starting to apply it to a real project and I am running into this issue.

    Here's part of my web.xml:
    My applicationContext.xml looks like this. (I changed the bean id and class names.)

       <bean id="beanOne" class="example.beanOne" singleton="false"/>  
       <bean id="beanTwo" class="example.beanTwo" singleton="false" init-method="init">
          <property name="beanOne">
             <ref bean="beanOne"/>
          <property name="dataSource">
             <ref bean="dataSource" />
    I am using the Spring Web MVC and here is my ServletName-servlet.xml file:

       <!-- Type of view to produce -->
       <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
          <property name="prefix"><value>/WEB-INF/jsp/</value></property>
          <property name="suffix"><value>.jsp</value></property>
       <bean id="stuffController" class="example.web.StuffController">
          <property name="beanTwo">
             <ref bean="beanTwo"/>
       <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
          <property name="mappings">
                <prop key="/showStuff.action">stuffController</prop>
    I put System.out.println in the constructors of beanOne and beanTwo. I reload the page and watch the command line. I only see the constructors for beanOne and beanTwo fire off once. Each time after that I get other messages I'm outputting, but not those bean's constructors.

    I haven't written any code that accesses any part of the Spring API. All the code I've written just uses my bean's methods.

    Any help would be appreciated.


  • #2
    The problem here is that the controller you are passing beanTwo into is a singleton and thus only gets created once. An instance of beanTwo is created when creating the controller and is injected into the controller using DI - that is it. Likewise, since you only have one instance of beanTwo you only get one instance of beanOne!

    To get around this problem check out section 3.3.3 in the Spring reference for information on method injection. This allows you more control over injection when dealing with beans with different lifecycles like a singleton and a non-singleton.



    • #3
      Thank you! I'll be looking into that tonight!