Tuesday, August 17, 2010

Spring Core, IOC examples for Novice Spring programmers.

Spring Hello World Program
Let's write a simple Hello world program using the spring way:

Bring the following jars in library path:

* dist/spring.jar
* lib/log4j/log4j-1.2.14.jar
* lib/jakarta-commons/commons-logging.jar


Write a HelloWorld Bean which has a method print message

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



Write the Spring configuration file. We will name it as context.xml. The name can be anything. Put the file somewhere in the classpath.







Write the main program :

String[] files = {"context.xml"};

//Start the context of Spring
ApplicationContext appContext = new ClassPathXmlApplicationContext(files);

//Get the Helloworld bean from spring context
HelloWorld helloWorld = (HelloWorld)appContext.getBean("helloWorld");
helloWorld.printMessage();



If you look into the main program than we are not creating the HelloWorld object ourself but we ask spring factory to return us an instance of HelloWorld object. This is the most important aspect of Spring, which is Ability to Create Objects. Spring essentially is a factory which creates objects for us.

Let's now say that we want to decouple the functionality of providing message to HelloWorld and pass that responsibility to a different class called HelloWorldMessage.
HelloWorldMessage:

public class HelloWorldMessage {
public String getMessage(){
return "HelloWorld";
}
}


And our HelloWorld class would look like

public class HelloWorld {
private HelloWorldMessage message;
public void setMessage(HelloWorldMessage message) {
this.message = message;
}
public void printMessage(){
System.out.println(message.getMessage());
}
}


Now HelloWorld has a dependency relationship and it needs an object of HelloWorldMessage. For that we need to modify the context.xml











The main class still remains the same. Here what we did is to use spring to build the relationship. This is another important aspect of Spring. To Wire the relationship..

Again to reiterate, the two important things that Spring bring to table is:

* Ability to create objects.
* Ability to build the relationship between objects.

The corollary is that if you are making instance of objects your self or building relationships yourself than you are not using Spring effectively.


These are basic premises of Inversion of Control(IOC) or DI(Dependency Injection). We will not get into theoretical debate here. But the important thing to understand is that the control of building objects and wiring relationships is delegated to the environment. You as an application developer go to the Spring container and ask for your object to do your work. The object is given to you created and all relationships set.

No comments: