Issue
I created two beans id referencing to the same class as below. I made bean1 to have a singleton scope and defaulted bean2 to singleton as well. In this case when executed.
Will two beans be initialized when i call either of the bean?
Will there be two singleton objects created for each?
<bean id="bean1" class="com.skanda.spring.core.ioc.HelloService" scope="singleton" /> <bean id="bean2" class="com.skanda.spring.core.ioc.HelloService"> </bean>
Calling Beans
public static void main(String[] args) {
BeanFactory beans = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
(BeanDefinitionRegistry) beans);
reader.loadBeanDefinitions(new ClassPathResource("mybeans.xml"));
HelloService service = (HelloService) beans.getBean("bean1");
}
Please advise.
Thxs, Skanda
Solution
You declared two singletons, so you have potentially two instances of HelloService
. If you had used an ApplicationContext
, both would have bean initialized at refresh time of the application context.
You are only using a BeanFactory, so you have no preinitialization (no refresh). When you call beans.getBean("bean1");
Spring initializes singleton bean1
and would have initialized its dependances if it had. As it has no dependances, only bean1
will be created, and bean2
will only be created if you ever call beans.getBean("bean2");
, or if Spring has to create it to resolve a dependance of another bean.
Answered By - Serge Ballesta
Answer Checked By - Cary Denson (JavaFixing Admin)