What is Spring?
- The Spring Framework is light weight and an open source application framework that aims to make J2EE development easier.
- Spring can be used for all layers or can be used for the development of a particular layer.
- Spring can be easily integrated with many of the existing frameworks like struts and Hibernate.
- Basic spring functions can works without any server (But web features requires server).
Why we need Spring?
- The J2EE architecture has excessive amount of repeated codes like JNDI lookups, Try/Catch blocks etc..
- By default J2EE supports distributed model, which may not needed by many small applications. So it simply uses lots of memory.
- EJB is very complex architecture and it supports only JTA (whereas Spring Supports JTA, Hibernate etc..)
- Spring has Dependency Injection support, which makes component plugging easier and helps in loose coupling.
We will learn how spring works and why we need spring by an example. The basic requirements and set up guide for the example is given below.
Basic Requirements:
- JDK (here used version 1.7 )
- Eclipse
- Spring Supported jar files. download Spring jars
- Application Server (If it is an Enterprise application)
Basic Setup
- Create a Java project in eclipse. (follow the java project wizard and create the project)
- Add the above mentioned jars in the class path (Right click on project name --> properties -->java build path --> Libraries --> add external jars )
- Now spring is ready to work.( see it is very simple and light weighted unlike EJB which requires a J2EE container to run even a small program)Note: The above setup is for standalone application creation with spring. For enterprise application, we can use the appropriate eclipse wizard like dynamic web application or we can use Maven based build tool structure. We will see each of these development in upcoming topics.
Note:
Spring can work in two versions,
- As a standalone application with the spring supported jars. (requires just JRE environment ) Or
- As a full fledged enterprise application with spring and other supported jars ( Requires Application server)The most of spring's concepts like IOC/DI , AOP can be understand easily with the standalone application itself. But the full usefulness of spring's features can be best understood only with the real time enterprise applications.
How Spring works?
Spring has many features like Dependency Injection (DI), Aspect Oriented Program (AOP), Spring security, Spring Database and Spring Web etc. But the basic feature is Dependency Injection which is used by all the other features.
So will see the example with the Dependency Injection. DI is also Called as Inversion of control (IoC). Why?
The general way of creating the instances in java is using new operator and we will set all it's properties manually. But in spring DI, we will be mentioning the configurations alone. But when to create the instance, what all the properties to be set,where to inject and when to inject all will be taken care by spring container.
To simply say, DI means injecting the dependencies in the right place and the right order. Beans will be configured either in a xml file or using annotations. Spring container manages the ordering, wiring and injecting the beans when and where necessary. For example, lets take 2 classes named State and City and it has the following properties.
State
public class State {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
City
public class City {
private String name;
private State state;
public String getName(){
return name;
public void setName(String name) {
this.name = name;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
If you see the above classes, State has a single property called "name"of type String. City has 2 properties called "name" of type String and "state" of type State. Consider our aim is to create a City object.
So see the traditional approach.
Traditional Approach
public class StateCityCreator {
public static void main(String[] args) {
State state = new State();
state.setName("Tamilnadu");
City city = new City();
city.setName("Salem");
city.setState(state);
System.out.println("City is :" + city.getName());
System.out.println("State is :" + city.getState().getName());
}
}
Spring Approach
In Spring, the objects and its dependencies are not created pro-grammatically. But they are configured as below using XML file. From spring3 these configurations can be done using annotations also .
XML configuration
What does the above configurations says? The first element "beans" in the above xml file is used as a namespace. This can be copy pasted from internet. The next element, "bean" is what we have to configure. If you notice there are 2 bean statements. Once is for state object and another one is for city object. They are mostly self explanatory. The first bean's name is configured with"state" and it's value is configured with "Tamilnadu". This is equivalent to,
State state = new State();
state.setName("Tamilnadu");
The same way city object is created as,
City city = new City();
city.setName("Salem");
city.setState(state);
Here the order of beans creation (First state has to be created, then City), wiring and dependency injection all are done by spring container.
Beans are created and can be accessed using the Spring ApplicationContext as follows.
[caption id="attachment_627" align="aligncenter" width="485"]
Spring ApplicationContext[/caption]
Java Code
package springintro;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StateCityCreator {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
City city = (City)context.getBean("city");
System.out.println("City is :"+city.getName());
System.out.println("State is :"+city.getState().getName());
}
}
The ApplicationContext is used to access the spring configuration file from the class path. (There are multiple application context implementations available to access the files differently).
When you call the context.getBean("beanname"), the object is fetched and ready to access.
You might be wondering why this much steps are required? why can't we use the traditional approach?
Why Configurations in XML File?
Till now we used State and City classes just for simplicity. But consider the real time applications like payment system.
[caption id="attachment_639" align="aligncenter" width="350"]
paymentsystem class diagram[/caption]
Consider the current implementation is done only with debit card service. But later we wanted to provide Credit card service instead of debit.So now If you have used the traditional approach,
To provide DebitCardService, the code might look like this,
PaymentSystem ps = new DebitCardService();
ps.authenticate();
So now in order to use the creditCardService, you have to change the code as below.
PaymentSystem ps = new CreditCardService();
ps.authenticate();
If you notice above, you can figure out the problem. The disadvantage here is code edit which is ugly. But if you use Spring approach, you can just change the implementation class in xml file, which does not affect you code. Thus the way spring gives easy plug-ability and loose coupling features.
To provide DebitCardService,
and your java code need not be changed.
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
PaymentSystem ps = (PaymentSystem)context.getBean("ps");ps.authenticate();
So based on your configuration in xml, the appropriate service is provided without changing the code.