When you first hear the word “Spring” your mind prints a beautiful picture like this,
But for Java developers, Spring is different but the feeling is similar 🙂
Spring makes it easy to develop web applications. It comes equipped with all sorts of different components that takes care of the important repetitive tasks for us.
A simple example would be the Bean injection or form validation. It’s all in there.
I also understand that Spring Framework could be a bit scary for newcomers but it’s all about understanding the basics. Once the basics are clear then spring is a breeze to work with.
By-the-way if you are just here to look at the code then follow this link
Table of Contents
What is Spring Framework?
Let’s leave Spring for sometime and concentrate on the term “Software Framework”. According to the hardcore definition of the term “Software Framework” –
A software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user-written code, thus providing application-specific software.
To understand in the easiest of the terms, let’s try to relate it with the real-world objects. Suppose, you have been given a task to create a single block of size 5X5 cm and you have been given a scale to measure that. It is a simple task for you, right? You will easily measure the size and create a block of the required size. But now imagine a situation where you have to create 10000 different blocks of varying sizes.
Now, what’s your approach going to be?
You cannot continue with your previous approach because that will take ages.
A new and better solution would be to make a fixture of a fixed size which will save you time doing the same thing again and again, i.e, measuring (writing same code).
If you have to make shapes with different sizes than you can add an additional feature to your fixture so that it can measure variable size.
This is what a framework does for you. You just have to adjust it according to your requirements. The hard part will be taken care of by the framework itself.
Similarly, if we talk about the Spring framework, it follows a usual flow, a life-cycle.
In this, you can hook your codes in between with the help of the Spring Lifecycle methods and the rest will be taken care of by the spring.
Actually it doesn’t feel like you hooking your code in between, it feels like Spring is wrapping your code inside its context elegantly. You will see once we write a small hello world application.
This will save you from writing the same code again and again and you will only be left with the implementation or we can say the business logic of the application.
In this way, Spring provides a more open yet structured framework using the dependency injection and Inversion of Control to decouple the dependencies between the modules. This enables us to easily integrate different pieces of technologies together to create a fast and scalable application.
Prerequisites
Before getting started with Spring application, there are a few concepts that you must be versed with.
Spring Container
I will not bombard you with a lot of information rather just tell you what it is at a very high-level.
You should know that Spring container is at the core of this framework.
Everything in Spring happens within a container. You can think of Container as a scope. Every object that is created in an application will live inside of this Spring container.
If you want to tell spring about any of your classes then this is the place to do so.
Spring Container will be responsible for all the wiring between the object (act of creating associations between objects), there configuration and lifecycle management.
Let’s go a tad bit deep to understand the structure of the framework.
When someone says container, he is usually talking about the Web Application Container. This is known as WebApplicationContext. There is another context that is called ApplicationContext.
So, here’s how they are linked together.
Application Context
Application Context is the root context. This is initialized in web.xml
. This could be used for loading up objects that will be used throughout the application. Like creating a Datasource bean that will be used across the application frequently. And there is only one application context.
Now the immediate question I asked was,
If Spring application context loads up all the required beans then who loads up spring context :/
Well Tomcat loads the Spring Context for the first time. And how does tomcat know which class to load. This is not a mystery. We tell tomcat where and what to load in the memory for the first time. And we do this by defining our configuration in the web.xml
file. Like this,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- ===================================================== -->
<!-- Can modify default root context config file -->
<!-- ===================================================== -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
There is one other way to load beans into the memory and by-the-way that is the most common way as well. It is by defining the Servlet.
Web Application Context
This is the child context of the root context. If you are only creating the servlet and not defining the ApplicationContext then this will act as the root context.
This is very we define the DispatcherServlet for our spring application.
Let me first show you how to define this servlet then it would be easy to walk through the process,
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- ===================================================== -->
<!-- One servlet, the dispatcher, to rule it all -->
<!-- ===================================================== -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
This bit is also defined in the web.xml
because we need a way to tell Tomcat how to hook our spring application to its context. After all we are just a big servlet running inside a Tomcat container :p
Here, we are defining a servlet and providing it a “url-pattern“. This URL pattern matches everything. This tells Tomcat to forward all the incoming requests coming to the system to…
Guess who did it pass all the incoming request to?
Spring, more specifically a Dispatcher Servlet.
Dispatcher Servlet is then responsible for routing the requests to the particular object (controller).
I think this is sufficient to start with Spring application. Now let’s understand the vocabulary that spring uses then we can create a small boilerplate application with the acquired understanding.
Spring Beans
Everything in the Spring framework is Bean. To make it very clear, the bean is nothing special and it is just a convention for creating classes.
A Java Bean is a java class that should follow the following conventions:
- It should have a no-arg constructor.
- It should be Serializable.
- It should provide methods to set and get the values of the properties, known as getter and setter methods.
Many developers will say that a bean is a POJO (Plain Old Java Object) class which is completely wrong. I don’t know why they say that.
A bean is just like a container to hold and structure data which makes it easier to set and retrieve data. Bean has a lifecycle defined in Spring framework.
Dependency Injection
DI is a design pattern which is used by the developers to decouple different working modules in an efficient way. It is a way to provide the service whenever required by the client. It is used to pass the dependency to the dependent object whenever it is required by the client. The basic approach of this pattern is to provide the client with the required service at the time he needs it rather than him searching for it.
DI also enables programmers to follow the Inversion of Control flow for the application which further helps to decouple the dependencies between two modules.
Inversion of Control (IoC)
As the name of the principle says Inversion of Control simply means that the natural flow of the application is unversed in order to decouple two different modules from each other. This is done with the help of abstraction. To achieve this a custom-written code is injected into the normal flow of the framework rather than calling different library functions. This is what the “Hollywood Participle” says,
Don’t Call Us, We Will Call You
In this case, the user or the client does not call the library methods explicitly rather framework itself calls the client code in its lifecycle. This helps to achieve a greater level of modules decoupling and helps the client to only concentrate on the business logic of the application rather than its flow of execution. A simple example of IoC – Example. If you are not satisfied and want to dive deeper then refer to this article – Inversion of Control and Dependency Injection.
Getting Started
[Update] Although the code that is copied below works, but I cannot vouch for it because I wrote it a long time back. For you folks, I’ve created a Spring boilerplate code with all the required configuration that you can get from the link below,
Even though the code is old I would encourage you to go through it. It will help you to understand different pieces and stitch them together.
First of all, you need all the required JARs before starting a project. You can find all the required JARs here… Simply download the folder and unzip anywhere on your pc from where you can easily access it from anywhere.
Getting Started
The first thing that you need to do before getting started with Spring Framework is to download all the required JARs. You can follow the download link here. Once you have downloaded all the JARs then it’s time for setting up the environment. I’m going to use eclipse mars which you can download from this link here (1st link). Just follow the step by step guide for setting up your workspace.
Here is a step-by-step process for setting up your project in eclipse. Just follow the steps mentioned below.
You have successfully setup your work environment. Now, you can start writing some code which will help you to better understand the working of Spring Framework.
This should be your file structure for this application. Now let’s write some code to make it work.
HelloWorld.java
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="helloWorld" class="in.varunshrivastava.beans.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
Conclusion
The most important thing is to understand the need of Spring Framework into your application. Once you know why you need a Spring Framework then you will find it easy to learn and it can save you hours of code. It is called a light-weight framework for JAVA. It is because you can get started with the minimum of the code. You do not need to use any of the Spring class or to extend it. You just plug your code into the Spring Framework and the rest is handled by the Spring itself. It can be used to build any Java application and makes application development bliss by providing powerful features like Dependency Injection (DI) and Inversion of Control (IoC).