Rajinder Menu

Explanation of Spring Hello World Example




This is very basic example which just prints “HelloWorld” on the console. But it shows, in general sense, how Spring use Inversion of Control (IOC) which is the core concept on which Spring framework is based upon.

In our example there are three files:

1)     HelloWorld,java
2)     MainApp.java
3)     applicationContext.xml

MainApp class is dependent on the HelloWorld class as it is using its instance to call the sayHello() method as:

public class MainApp{
 
   public static void main(String args[]){
      ...
      ...
    /*helloBean is an instance of HelloWorld class.*/
    helloBean.sayHello();   
  
  }
}



What is important here is that how MainApp class is obtaining the instance of HelloWorld
object. Here MainApp is not using “new” keyword in order to create HelloWorld instance like this:

public class MainApp{
 
   public static void main(String args[]){
  
   HelloWorld  helloBean = new HelloWorld(); 
       
   helloBean.sayHello();   
  
  }
}



But, instead, it is requesting HelloWorld instance from the Spring Container using factory method getBean().

public class MainApp{
  public static void main(String args[]){
 
  ApplicationContext ac=new    
 ClassPathXmlApplicationContext("resources/ApplicationContext.xml");

  HelloWorld helloBean=(HelloWorld)ac.getBean("hello");
  helloBean.sayHello();

  }
}

In the first statement of above class,

ApplicationContext ac=new
ClassPathXmlApplicationContext("resources/ApplicationContext.xml");

we are creating an instance of Spring IOC Container (ApplicationContext) and passing it the path of bean configuration file ApplicationContext.xml relative to the classpath.

Spring Container (ac) will then read bean definition of HelloWorld class from ApplicationContext.xml and creates its instance which is obtained by MainApp by getBean() method.



Thus responsibility for creating and managing objects has been transferred from our application code (MainApp) to Spring Container. MainApp is only ‘using’ the HelloWorld instance. Hence Inversion of Control is taking place as control of creating object is inverted from our class to Spring Container itself.  

Note here IOC is taking place in respect of responsibility for creating objects not from Dependency Injection point of view. In this program DI is not taking place. IOC is very general term. DI is just one way to implement it. Here we are using IOC along with factory method getBean().


I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment