Home > Java, Spring > Spring Framework – Introduction

Spring Framework – Introduction

Spring is an open source framework which can be used in developing java applications. The main principle behind the spring is dependency injection.

What is Dependency injection ?

This is also called as dependency inversion. The main idea behind this is decoupling the dependency between objects.
Take a look at the following code.

public class Shape
{
public void draw() {}
}
public class Triangle extends Shape
{
public void draw() { }
}
public class Circle extends Shape
{
public void draw() { }
}
Now we are going to call the above objects.
<code></code>
public void drawMethod(Shape shape)
{
shape.draw();
}


In the above method we have removed those dependencies of both Circle and Triangle.

Shape shape = new Triangle();
drawMethod(shape);

But in here we have tied to this new triangle. So we need to get rid from this. So what we going to do is take this dependency out from the class. The class will not know that what shape would be drawn. We use a separate class to provide a shape.

protected class Drawing{
private Shape shape;
public setShape(Shape shape){
this.shape = shape;
}
public drawShape(){
this.shape.draw();
}
}

& then we use a class to inject the dependency for above class.

Triangle t = new Triangle();
drawing.setShape(t);
drawing.drawshape();

Likewise we do not need to modify the drawing class. The dependency is done through a separate entity. So we have successfully decoupled the dependency. In Spring what we do is that we do not need to write the class. We just say spring to inject the relevant dependency.

Spring Factory Bean

Normally Spring acts as a Bean container. So any POJO (Plain Old Java Object) can be stored in the container. All the objects which are inside the container are properly managed. The creation of this object is done by Spring. In the Spring framework, the objects are created according to the factory pattern. That means if a object is needed to be instantiated inside a separate object, it does not simply done by new keyword. Instead of that, the we write to Spring to instantiate the object and pass it to the outer object. The Spring XML file contains the bean definitions for the creation of objects. So by changing this XML, we can add our own features to the objects.

Advertisements
Categories: Java, Spring
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: