jeudi 26 mars 2015

Spring loads two different instances when loaded with BeanFactory and ApplicationContext with a single spring.xml file

I was writing some code to study different ways for getting bean from spring container. I have kept the code very simple to address the issue I had .


I have written below classes


Triangle Class



package org.studyspring.beanfactory;
public class Triangle {
public String draw() {
return "Triangle Drawn";
}
}


Spring.xml



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/1jdM0fG">
<bean id ="triangle" class ="org.studyspring.beanfactory.Triangle"/>
</beans>


Test class



package org.studyspring.beanfactory;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;

import static org.junit.Assert.assertEquals;

public class BeanFactoryTest {
private static BeanFactory factory;
private static ApplicationContext context;

@BeforeClass
public static void setupBeforeClass(){
factory = new XmlBeanFactory(new FileSystemResource("./basicSpring/src/test/resources/spring.xml"));
context= new ClassPathXmlApplicationContext("spring.xml");
}

@Test
public void getTriangleBean_WithBeanFactory(){
Triangle triangle = (Triangle) factory.getBean("triangle");
String message = triangle.draw();
assertEquals("Triangle Drawn",message);
}

@Test
public void getTriangleBean_WithApplicationContext(){
Triangle triangle = (Triangle) context.getBean("triangle");
String message = triangle.draw();
assertEquals("Triangle Drawn",message);
}

@Test
public void triangleBean_ShouldBeSame_WithApplicationContextAndWithBeanFactory(){
Triangle triangle = (Triangle) factory.getBean("triangle");
Triangle triangle1 = (Triangle) context.getBean("triangle");
String message = triangle.draw();
assertEquals(triangle,triangle1);
}
}


I thought my testcase triangleBean_ShouldBeSame_WithApplicationContextAndWithBeanFactory should have been passed but actually it failed with below error



Expected :org.studyspring.beanfactory.Triangle@22c1609b
Actual :org.studyspring.beanfactory.Triangle@45ad71f0


I am asking this question because I had below assumptions




  1. when spring container initializes a bean its default scope is Singleton




  2. spring container should use only one instance of bean




  3. moreover ApplicationContext extends BeanFactory (indirectly)




  4. We could use BeanFactory and ApplicationContext alternatively




My question is about the fundamentals ,is it the correct behaviour by spring container to load two seperate instances each for beanFactory and ApplicationContext ?


Aucun commentaire:

Enregistrer un commentaire