Archive for the ‘Spring’ category


Introduction to Java Spring Framework

“Spring is a light weight Dependency Injection and Aspect Oriented Container and framework”

I will illustrate you by a basic example code how spring provide way to decouple classes. Hence, spring framework facilitates to separate software logic in independent layers or module.

Let’s suppose we want to travel to some place. In object world the travel can be defined as fallowing

class Airplane
{
    public void move()
   {

 System.out.println(“move”);
   }
}
class Travel
{
public static void main (String[] args)
{
   Airplane airplane = new Airplane();
   airplane.move();   //move from one place to other
}
}

In above code we are stuck with Airplane. If we want to travel using ship, bike, car or bus, we would have to change both reference and object creation side in line 5 of Travel class.
Technically, this is an example of tightly coupled class, which is a bad thing.

Now, I will modify the above code a bit to address the issue.

interface Vehicle
{
void move();
}
class Airplane implements Vehicle
{
    public void move()
   {

 System.out.println(“move”);
   }
}
class Travel
{
public static void main (String[] args)
{
   Vehicle v = new Airplane();
   airplane.move();   //move from one place to other
}
}

This code is better than the first version. But, you can notice on line 5. Though I get rid of Airplane reference ; I am still instantiating concrete class Airplane using the “new” operator. Hence the Travel class is still dependent on Airplane i.e. coupling still exists.

Now modifying the above code to use Spring to decouple travel class.

public class Travel
{
public static void main(String[] args)
  {
    ApplicationContext apc = new ClassPathXmlApplicationContext(“spring.xml”)
    Vehicle v = (Vehicle)apc.getBean(“vehicle”);
    v.move();
 }
}

Our objective is achieved. Travel is no more dependent on Airplane or any other vehicle type in travel. Vehicle type is specified by external config file spring.xml

Please note there is no “new” operator in Travel. The travel is independent and modular.

The example spring.xml







. . . . . .  … .


Or

. . . . . .


. . . . . .  … .