Search This Blog

Saturday, 4 February 2012

The Spring Container

In our previous post we saw how the BeanFactory was used. If the same code was to be written without spring
public static void main(String[] args) {
//    Resource res = new ClassPathResource("beans.xml");
//    XmlBeanFactory beanFactory = new XmlBeanFactory(res);
//    HelloWorldMessanger messager = (HelloWorldMessanger) beanFactory.getBean("messager");
    HelloWorldMessanger messager = new HelloWorldMessanger();
In the traditional approach to creating object associations, we write lookup code or use constructors. Complex Object hierarchies are managed by Factory patterns, Builders, Service Locators etc. There is JNDI lookup code written by us to locate and use our service objects at different points in our code. Static methods that we use to create complex objects. At some point it all begins to look complex to understand and use and very difficult to test.
In Spring it is not objects who are responsible for finding objects or creating them. They do not need to talk with Factories and Builder methods to get any objects they need. This job is delegated to the Spring container. The Spring container once provided with the relevant information (our XML file) is capable of creating the objects and configuring them. By configuring I mean setting up associations( filling their inner property fields). So if there was a car object to be created, The Spring container would be capable of creating instances of the appropriate engine, gear- box, seating etc. It would then create the car object and assign the above objects to the car.(This is a very simplified example of what is also known as Dependency Injection) This process of configuring objects is what we call wiring.
The Container is the heart of the spring-framework. There are a variety of Containers available in Spring. One of them we saw in our previous example - org.springframework.beans.factory.xml.XmlBeanFactory. The containers can be grouped into two teams - The BeanFactory team and the ApplicationContext team.
The XmlBeanFactory that we saw in the previous post is a type of BeanFactory (Interface). The BeanFactory defines the simplest type of Containers. It provides  support for
  • dependency injection 
  • and life cycle interfaces. 
The ApplicationContext interface actually extends the behavior of the BeanFactory. It provides a host of additional functionalities such as
In short the ApplicationContext is a much more powerful version of the BeanFactory. In coming posts we shall look deeper into the BeanFactory and then move towards the ApplicationContext based Containers.

No comments:

Post a Comment