Spring part 1 [IOC Containers]


IOC container contains two types of containers which are core container and another is advanced J2EE container. Core container is called BeanFactory and J2EE container is called ApplicationContext also one more Configurable Application Context.

So we may be thinking like what actually the containers do?

  1. They create a instances for the POJO classes.
  2. manage lifecycle of POJO classes.
  3. they can also do dependency Injection in POJO classes.


Then there may be a question what is the difference between the two types of containers? Here the core containers will initialize the object upon the user request where as the ApplicationContext will create the object at the compile time to be used for the user. Lets say we have a class named Demo. Now lets say we are defining the beans of the Demo in the xml file like

...
<beans>
    <bean id="demo" class="Demo" />
</beans>
...

Lets say while using the application user need the object the Demo then using the core container the IOC will create a new object for the user only when user request for it. But the ApplicationContext will eagerly creates the object while running the app and when user want the object it will provide the created or provide the reference of the created object to the user. By default the the bean creation scope is singleton which means it can be created only once and later whoever want that object it will reference the previous of firstly created object. But we can use several scopes methods like prototype, session, global session etc. Fo example if we have used the prototype scope then the IOC will create the new object upon each user requests, but will not create any object at the beginning.

...
<beans>
    <bean id="demo" class="Demo"  scope="prototype"/>
</beans>
...


1. Bean Factory Container

public static void main(String args[]){
   Resource res = new ClassPathResource("YOUR_XML_FILE_NAME.xml");
   BeanFactory factory = new XmlBeanFactory(res);
   Demo d = (Demo) factory.getBean("demo"); //typeCast because factory always return Object type
}

2. ApplicationContext Container

public static void main(String args[]){
  ApplicationContext app = new ClassPathXmlApplicaitonContext("some_location/your_xml_file.xml");
  Demo d = (Demo)  app.getBean("demo");
}


How the IOC creates the object ?
1. User request IOC to provide the instance of some class by using the bean id/name
2. Then IOC will look up for the bean with given id/name in the bean configuration file and take the name of the class
3. It execute the method called Class.forName("Demo").newInstance();

0 comments:

Post a Comment