Thursday, October 1, 2015

Spring Framework - 3 - Spring container Bean creation

The whole concept of Dependency injection is possible because, the whole of Spring container is a factory of POJOs. It creates and manages the initiation and destruction of Bean objects. Spring uses the Factory design pattern, where there's a factory class that generates the objects we want based on the received specifics.

Let's get practical,

1)Create another class, Triangle with void Draw() method that prints "Triangle" in it.
    public class Triangle {
public void Draw()
{
System.out.println("Triangle Drawn");
}
  }
note
while creating POJO's, mandatory to create default constructor, else results in org.springframework.beans.factory.BeanCreationException


2)Create a java class with main method in it, say "DrawingApp" which instantiates Triangle as below.
public class DrawingApp {
public static void main(String[] args) {
Triangle triangle = new Triangle();
triangle.Draw();
}

}


Now, if we are using Spring in the above scenario, we will be

1)coding the DrawingApp as below:

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;

public class DrawingApp {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
}
}

2)create the spring.xml

  • Create a spring.xml under the project src folder. Copy and paste the DOCTYPE tag from other files(ex:application-context.xml) from teh spring installation folder, or simply paste the below code into the spring.xml file, <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
  • Now, specify the bean that the container needs to initialise as below:

<beans>
<bean id="triangle" class="com.project.springDemo.Triangle"></bean>
</beans>

3)Now, Update DrawingApp class as below to access the Triangle object that is instantiated from the Spring container,
public class DrawingApp {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
                Triangle triangle = (Triangle) context.getBean("triangle");//Id of bean in spring.xml 
                triangle.Draw();
}
}

If we now execute this class(DrawingApp, It will print system.out from Draw() method.

-----------------------------------------------------------------------------

No comments:

Post a Comment