Sunday, July 26, 2009

Simple usage of Spring

Let us look into the concept of Dependency Injection through a small example:-

Here we are trying to print out a string "Hello World" using Spring's techniques. The interface HelloService defines the contract for the service class:-

package com.hello;
public interface HelloService {
void sayHello();

HelloServiceImpl implements the above interface as follows:

package com.hello;
public class HelloServiceImpl implements HelloService {
private String hello;
public HelloServiceImpl() {}
public HelloServiceImpl(String hello) {
this.hello = hello;
public void sayHello() {
public void setHello(String hello) {
this.hello = hello;

The property "hello" in this class can be set either through the constructor or the setter method. Now, let us write the Spring Configuration file, named here as hello.xml

Here, the bean named "helloService" of class "HelloServiceImpl" has a property "hello", which is injected with a value of "Hello World" using the setter injection. In effect, this does the following:-

HelloServiceImpl helloService = new HelloServiceImpl();
helloService.setHello("Hello World");

If we were opting for constructor injection, then the tag in the xml file would have to be replaced with -

In effect, this does the following:-

HelloServiceImpl helloService = new HelloServiceImpl("Hello World");

Now, let us write a main class for this entire application, -

package com.hello;
//add imports and handle exceptions as and when necessary
public class HelloMain {
public static void main (String[] args) {
BeanFactory factory = new XmlBeanFactory(
new FileSystemResource("hello.xml"));

HelloService helloService = (HelloService) factory.getBean("helloService");


Here, the BeanFactory is the Spring container. The configuration file "hello.xml" is loaded, "getBean()" retrieves a reference to the bean with id "helloService" and this reference is used to print "Hello World" to the screen.

This example depicts Dependency Injection or Inversion of Control in Spring clearly. Typically, in almost all applications, each object would be responsible for obtaining its own references to the objects it collaborates with, which leads to highly-coupled and hard-to-test code. But here, objects are given their dependencies at creation time by the xml file (in the above example) or dependencies are injected into objects, hence enabling loose-coupling. Here, the interface helps the class to remain loose-coupled at all times.

reference :- Spring in Action

No comments:

Post a Comment