• Skip to main content
  • Skip to primary sidebar
BMA

BeMyAficionado

Inspire Affection

Getting Started With Spring Framework in less than 30 minutes

August 11, 2016 by varunshrivastava Leave a Comment

When you first hear the word “Spring” your mind prints a beautiful picture like this,

Beautiful Spring

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

  • Spring MVC Boilerplate With XML Configuration

Table of Contents

  • What is Spring Framework?
    • Prerequisites
    • Spring Container
    • Application Context
    • Web Application Context
    • Spring Beans
    • Dependency Injection
    • Inversion of Control (IoC)
  • Getting Started
    •  
  • Conclusion

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.

SpringOverview

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.

SpringBeans

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.

dependency-injection

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)

inversion of control

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,

  • Spring Boilerplate With XML Configuration

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).

  • Thinking in OOPs: Object-Oriented Programming

Related

Filed Under: Programming Tagged With: basics, framework, hello world, java, spring, spring framework, tutorial

Primary Sidebar

Subscribe to Blog via Email

Do you enjoy the content? Feel free to leave your email with me to receive new content straight to your inbox. I'm an engineer, you can trust me :)

Join 874 other subscribers

Latest Podcasts

Recent Posts

  • Is The Cosmos a Vast Computation?
  • Building Semantic Search for E-commerce Using Product Embeddings and OpenSearch
  • Leader Election with ZooKeeper: Simplifying Distributed Systems Management
  • AWS Serverless Event Driven Data Ingestion from Multiple and Diverse Sources
  • A Step-by-Step Guide to Deploy a Static Website with CloudFront and S3 Using CDK Behind A Custom Domain

Recent Comments

  • Varun Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Vaibhav Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Varun Shrivastava on Should Girls Wear Short Clothes?
  • D on Should Girls Wear Short Clothes?
  • disqus_X5PikVsRAg on Basic Calculator Leetcode Problem Using Object-Oriented Programming In Java

Categories

  • Blogging
  • Cooking
  • Fashion
  • Finance & Money
  • Programming
  • Reviews
  • Software Quality Assurance
  • Technology
  • Travelling
  • Tutorials
  • Web Hosting
  • Wordpress N SEO

Archives

  • November 2024
  • September 2024
  • July 2024
  • April 2024
  • February 2024
  • November 2023
  • June 2023
  • May 2023
  • April 2023
  • August 2022
  • May 2022
  • April 2022
  • February 2022
  • January 2022
  • November 2021
  • September 2021
  • August 2021
  • June 2021
  • May 2021
  • April 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • February 2020
  • December 2019
  • November 2019
  • October 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • January 2019
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016

Tags

Affordable Hosting (4) algorithms (4) amazon (3) aoc-2020 (7) believe in yourself (4) best (4) database (4) earn money blogging (5) education (4) elementary sorting algorithms (4) experience (3) fashion (4) finance (6) Financial Freedom (7) food (7) friends (3) goals (5) google (5) india (10) indian cuisine (5) indian education system (4) java (16) life (16) life changing (4) love (4) make money (3) microservices (9) motivation (4) oops (4) podcast (6) poor education system (4) principles of microservices (5) problem-solving (7) programmer (5) programming (28) python (5) reality (3) seo (6) spring (3) success (10) success factor (4) technology (4) top 5 (7) typescript (3) wordpress (7)

Copyright © 2025 · Be My Aficionado · WordPress · Log in

Go to mobile version