Announcement Announcement Module
Collapse
No announcement yet.
Bean not initalized until referenced? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Bean not initalized until referenced?

    I have a simple main() that creates a XmlBeanFactory. After creation I expected that the beans I defined in my beans.xml file would have been initialized (i.e., constructors called). This does not happen. Here are the contents of beans.xml:

    <beans>
    <bean id="Foo" class="Foo">
    <constructor-arg><ref bean="Bar"/></constructor-arg>
    </bean>

    <bean id="Bar" class="Bar"/>
    </beans>

    Adding the following line to my main() implementation resulted in the Foo & Bar constructors getting called:

    Foo foo = (Foo)factory.getBean("Foo");

    My understanding of the Bean lifecycle is that beans are fully initialized (i.e., constructors called and applicable properties set) after the BeanFactory is created (assuming that the bean is a singleton (default) and not lazy-init (also default) ).

    Am I misunderstanding the lifecycle or perhaps misconfiguring Spring?

    Thanks,
    Rich

    P.S. - My intent is to use Spring to deploy arbitrary services that present remote interfaces. That is, the clients don't necessarily reside in the same JVM. So I really don't want main() to have to be aware of and explicitly reference the beans to initialize them as shown in the above code snippet. That's what I want the BeanFactory to do.

  • #2
    Hi Rich,

    The DefaultListableBeanFactory.preInstantiateSingleton s method should instantiate all singletons, regardless of whether lazy-init is true or false (I think). I think when you are using an XmlBeanFactory, you have to call this method after creating the factory to ensure singletons are instantiated prior to accessing them.

    For some reason, I think ApplicationContext implementations may handle this differently, so you could try using a ClassPathXmlApplicationContext and see if the default is any different.

    Good luck!

    -Arthur Loder

    Comment


    • #3
      Arthur,

      That did the trick (I used preInstantiateSingletons()), many thanks!

      Cheers,
      Rich

      Comment

      Working...
      X