Rajinder Menu

Spring 'Hello World' Example with Loose Coupling.




This example is same as HelloWorld example and prints HelloWorld on console. But, in addition, it also shows how to implement loose coupling in your code. This  example is explained here.

This example is using following technologies:

1) Spring-framework-3.0.2.RELEASE 
2) Eclipse Java EE IDE Helios Release (Eclipse version 3.6)
3) Java SE 6 

Note: The Spring 3.0 requires at least Java 1.5. 

Step1:Create anew project.

Create a new Spring project in eclipse as we did in previous HelloWorld example and name it as SpringHelloWorldLoose. Our project structure is :
 




Step2: Adding Source Code

Our project has four files: 

1) HelloInterface.java (An interface)

2) HelloWorld.java (Implementation of above interface)

3) MainApp.java (File containing main() function to execute the project)

4) ApplicationContext.xml ( File containing bean configurations)

Add following source to them.

HelloInterface.java

package examples.spring.helloworld; 

public interface HelloInterface{ 
   public void sayHello(); 
}

HelloWorld.java
package examples.spring.helloworld;

public class HelloWorld implements HelloInterface{
    public void sayHello(){
      System.out.println("Hello World!");
   }
}

MainApp.java
package examples.spring.helloworld;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp{
   public static void main(String args[]){
      ApplicationContext ac=new ClassPathXmlApplicationContext("resources/ApplicationContext.xml");
      HelloInterafce  helloBean=(HelloInterface)ac.getBean("hello");
      helloBean.sayHello();
   }
}


ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="hello" class="examples.spring.helloworld.HelloWorld"/>

</beans>

Step3: Adding Jars

In order to run your project you need to add required jars to it. Following jars will be required:

1) org.springframework.beans-3.0.2.RELEASE.jar
2) org.springframework.core-3.0.2.RELEASE.jar
3) org.springframework.context-3.0.2.RELEASE.jar
4) org.springframework.asm-3.0.2.RELEASE.jar
5) org.springframework.expression-3.0.2.RELEASE.jar
6) commons-logging-1.1.1.jar 

You can download commons-logging-1.1.1.jar from here. Other Spring framework related jars can be found in dist folder of your downloaded Spring distribution zip file


To add above jars right click on your project then go to Build Path > Configure Build Path.


Click on Add External JARs... . Go to the location where you have stored your jars. Add them one by one.


Step4: Executing the Program 

Right Click on the project and go to Run As > Java Application.

You will see the output "Hello World!" in the Console Pane at bottom.



Explanation >>




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


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.


Explanation of HelloWorld example with Loose Coupling




This example is same as our HelloWorld example (without loose coupling) and prints HelloWorld on the console. In previous HelloWorld example we have seen how Spring used IOC design pattern in order to move the control for creating objects out of our application code to Spring framework. This example does the same thing but it also adds one more important design principle known as loosely coupled code.
Though this example is very trivial to show the benefits of loosely coupled code but still it will fulfil its purpose for the beginners.

Our example has four files:

 1) HelloInterface.java (An interface)

2) HelloWorld.java (Implementation of above interface)

3) MainApp.java (File containing main() function to execute the project)

4) ApplicationContext.xml ( File containing bean configurations)

In previous HelloWorld example we have seen that MainApp class is using HelloWorld class directly. It is directly dependent on HelloWorld class making our code tightly coupled with it.

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



But in this example MainApp class is not using HelloWorld class directly. Instead it is using an interface HelloInterface. HelloWorld implements HelloInterface.

public class MainApp{
public static void main(String args[]){
    ...
   HelloInterface helloBean=(HelloInterface)ac.getBean("hello");
  helloBean.sayHello();
 }
}


Now as we have removed the direct dependency of MainApp from HelloWorld class, our code becomes loosely coupled.

Suppose there is another class SecondHelloWorld which also implements interface HelloInterface.

public class SecondHelloWorld implements HelloInterface{
  public void sayHello(){
   System.out.println("I am saying Hello again!");
 }

Above class is same as HelloWorld class but prints some different message.

Now if we want MainApp to use SecondHelloWorld class instead of HelloWorld class, all we have to do is just change bean configuration in ApplicationContext.xml like this: 

<beans .... >

   <bean id="hello" class="examples.spring.helloworld.SecondHelloWorld/>

</beans>


We have not touched our application code (MainApp) and our implementation of HelloInterface got changed.



That’s the beauty of loosely coupled code. Due to loosely coupled code we have removed the implementation details from our main application code. If later we want to change the implementation we can do that with minimum of changes.

Conclusion:

1)      Due to IOC we have moved creation of objects out of our code to configuration file. Thus freeing our code from the responsibility of creation and management of objects.

2)      Due to loose coupling we have removed implementation details out of our code.

3)      And since our application code does not depends on implementation and also does not creating objects using  new’ keyword, whenever we need to change the implementation all we have to do is to change the bean definition in configuration file (ApplicationContext.xml) only.
   
     Otherwise to change the implementation of HelloInterface we would have to change our application code of MainApp and recompile it like this :
         
      public class MainApp{
 
   public static void main(String args[]){
  
   HelloInterface  helloBean = new SecondHelloWorld(); 
       
   helloBean.sayHello();   
  
   }
}

  
    Changing in code like above in small example like this one, does not seems problematic but in large projects changing like this at several places matters!

 
  
 



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


Spring 'Hello World' Example using Eclipse


In this tutorial I am going to show how to create and execute a basic Spring program using Eclipse IDE. This example is explained here.

This example is using following technologies:

1) Spring-framework-3.0.2.RELEASE 
2) Eclipse Java EE IDE Helios Release (Eclipse version 3.6)
3) Java SE 6 

Note: The Spring 3.0 requires at least Java 1.5

Step1: Download Spring Framework

Download Spring 3.0.2 release from here. After it unzip the downloaded zip file to an appropriate folder. You will see the following contents under unzipped folder.




The dist folder contains various jar files which you will need for your Spring based application.

Step2: Setting Up Spring Project in Eclipse

Open Eclipse and go to File > New > Java Project a shown below: 




Upon clicking on Java Project you will see following figure.



































In the field Project Name, enter the name for project as SpringHelloWorld and click next. Following figure will come up.



































Enter value for field Default output Folder as SpringHelloWorld/build and click finish. You will see the following figure.
































 

You can see the newly created SpringHelloWorld project in above figure.

Now your project has been created. Let's add some source code to it.

Step3: Adding Source Code

Our project has three files: 

1) HelloWorld.java

2) MainApp.java (File containing main() function to execute the project)

3) ApplicationContext.xml ( File containing bean configurations)

Let's add these files in eclipse one by one.

Right click on src folder under SpringHelloWorld project and go to New > Class to create a new java class. Enter the name of class as HelloWorld and name of package as examples.spring.helloworld as shown in following figure.





 Similarly create a another class named MainApp.java in the same package.

 Enter following code to both files:

HelloWorld.java
package examples.spring.helloworld;

public class HelloWorld{
public void sayHello(){
System.out.println("Hello World!");
}

}
MainApp.java
package examples.spring.helloworld;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

Under src folder create a new folder named resources.Under resources folder create a new file and name it as ApplicationContext.xml.

Your project structure will look like this:



Add following code to applicationContext.xml

ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="hello" class="examples.spring.helloworld.HelloWorld/>

</beans>

Step4: Adding Jars

In order to run your project you need to add required jars to it. Following jars will be required:

1) org.springframework.beans-3.0.2.RELEASE.jar
2) org.springframework.core-3.0.2.RELEASE.jar
3) org.springframework.context-3.0.2.RELEASE.jar
4) org.springframework.asm-3.0.2.RELEASE.jar
5) org.springframework.expression-3.0.2.RELEASE.jar
6) commons-logging-1.1.1.jar 

You can download commons-logging-1.1.1.jar from here. Other Spring framework related jars can be found in dist folder mentioned in Step 1.


To add above jars right click on your project then go to Build Path > Configure Build Path.You will see following figure.



Click on Add External JARs... . Go to the location where you have stored your jars. Add them.

You can see jars added to SpringHelloWorld Project in the Package Explorer tab as shown in following figure.



Step5: Executing the Program 

Right Click on the project and go to Run As > Java Application.

You will see the output "Hello World!" in the Console Pane at bottom.


Explanation >>







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