Spring Framework Tutorial: Quick Help with Java Open Source

springframeworktutorialIntroduction to Spring Framework

As you may be aware, Spring Framework is an open source platform from Java, which offers a complete infrastructure platform for quick and easy development of Java applications. Java’s Spring Framework was created by Rod Johnson under the license of Apache 2.0.  Version 4.0 is the latest version of Spring Framework released earlier this month.

Java Spring Framework is one of the most loved enterprise Java development framework.  Developers across the world use Spring Framework to develop robust, high functioning and reusable application. The most basic version of Java Spring Framework sizes around a few Megabytes, which shows it lightweight virtue combined with its framework transparency.

Spring Framework’s core features can be used to develop all kinds of Java applications. However, there are a few other extensions to build web applications on top of J2EE platform. Hence, Spring Framework is created to ease the use of J2EE development environment and enable developed to follow genuine programming practices by introducing programming model based on POJO.

Understanding Basic Spring Framework Architecture:

1. Database Integration – As name suggest, this module is specifically designed and included for Database Integration – As name suggest, this module is specifically designed and included for providing interface for connecting application UI and its back-end to database while developing enterprise applications.

 List of sub-modules covered inside database integration module:

1. JDBC
2. ORM
3. OXM
4. JMS
5. Transactions

2. Web (Remote/MVC) Development – Web development module is essentially designed for development of web-based applications with the use of Spring Framework. Web Development based on MVC and is well organised. If you are developing only web-based applications you can just install this module alone.

List of sub-modules covered in the Web development module:

1. Web
2. Servlet
3. Porlet
4. Struts

3. Core Container – The Core Container module contains the core java development  functionalities. Code Container is the most essential module for all developers due to its basic offering.

4. List of sub-modules covered in code container module.

1. Beans
2. Core
3. Context
4. Expression Language

5. AOP, Aspects and Instrumentation are three other modules of Spring Framework. However, it is essential that you have prior knowledge of Core Java to understand Spring Framework in detail.

Spring Framework has a great feature of reliable transaction management interface which allows to scale down to local transactions (i.e., without using multiple dbs) and scale up to a global transaction (i.e., with the use of JTA).

Understanding Spring Fundamentals

Spring Container

Spring Container makes a core or a heart of the Spring Framework. Spring Container is utilized to create objects, wiring them with each other, configuring them and managing the complete lifecycle of these objects (from their creation till their destruction). The objects are known as spring beans, which we will discuss later in the tutorial.

With the help of the provided configuration metadata, Spring Container decides the initiating, configuring and assembling particular objects.  The configuration metadata input to Spring Container is built either in Java or XML.

The Following diagram gives you a high-level overview about the working of Spring Framework works. As shown in the figure, Spring container uses the POJO classes in combination with configuration metadata to create a high-performing and fully configured executable application.

Basically, Spring provides two different types of containers:

1. Bean Factory Container

Bean Factory is the simplest container that provides support for DI. The interface is defined by “theorg.springframework.beans.factory.BeanFactory.” The bean factory related interfaces like DisposableBean, InitializingBean, BenFactoryAware still exists in the Spring Framework simply for supporting backward compatibility to numerous third-party frameworks..

2. Application Context Container

The Application Context Container is more of an enterprise specific functionality which supports complex tasks like resolving text messages from property files as well as publishing application events to subscribed event listeners.

Basically, Application Context container supports all the functionalities offered by Bean Factory container. Bean Factory is used for few light-weight applications such as mobile apps where speed and data volume has a higher significance.

Spring Beans

As we referred in the section of Spring Container, Spring beans are those objects that outline the backbone of the application and managed by Spring containers. A spring bean is an object which can be instantiated, assembled and managed by Spring container. The beans are defined with the help of configuration metadata input to the container, i.e. <bean/> in the XML configuration file defines a bean for the application.

The spring bean definition has the information related to configuration metadata which container requires getting the below details:

  • How bean has been created?

  • Lifecycle details of a bean

  • Dependencies of a bean

Above mentioned configuration metadata have a few important sets of properties that help creating each bean’s definition:

Class

Properties

Scope

Name

Constructor-arg

Initialization method

Destruction method

Autowriting mode

Scope of a Spring Bean

In the Spring Framework, developer has an option of defining a scope of a spring bean. i.e. To allow spring to create a bean instance every time new one is required, developers should declare the scope attribute of a bean as a prototype. If a developer wants Spring Framework to return the similar bean instance at every requirement, scope attribute of bean shall be declared as singleton.

There are five scopes supported by Spring Framework. However, there of them can be availed only with the web-aware Application Context container:

  1. Singleton – Scope allows the bean definition of single bean instance per single spring container.

  2. Prototype – Scope allows the definition of N number of bean instances for a bean in any container.

  3. Request – Scope allows a bean definition of type HTTP request only. Request scope is valid only for application context spring container.

  4. Session – Scope allows a bean definition of type HTTP Session. Just like request scope, its valid only for application context spring container.

  5. Global session – Scope allows a bean definition of type HTTP session. Valid with application context spring container.

Lifecycle of a Spring Bean

It is as easy as understanding the lifecycle of a class object in C++. Just like an object, bean is defined to perform few important initializations for bean to become a useful entity. Similarly, the bean is removed from the spring container when it is not longer need and subsequent some cleanup activities are performed.

Even though, there is a long list of activities performed behind the curtains by a bean between its initialization and destruction, we would discuss only two callback methods of a bean’s lifecycle which are needed during the bean initialization and at the time of destruction.

In order to define instantiation and destruction of the bean, developers can declare a spring bean with <bean> tag with init method and destroy method respectively. Attribute specified with the init method would be called immediately after the bean instantiation and attributes with destruction method would be called just before the bean destruction (or just before the bean is removed from the container).

Bean Initialization

org.springframework.beans.factory.InitializingBean is a single method for the bean initialization callback. Method void afterPropertiesSet() is used for throwing exception. This simply means that developers can implement initialization methods inside afterpropertiesSet() function.

In case if xml based configuration metadata is being used, init-method attribute can be used for specifying a method or a function name with no arguments and void return signature. i.e.

<bean id = “SampleBean”
        Class = “Samples.SampleBean” init-method = “initsample”/>

Here is a sample class definition

Public class SampleBean
{
        Public void initsample()
        {
        //Bean Initialization
        }
}

Destruction Callback

Interface org.springframework.beans.factory.DisposableBean defines a single method for destruction similar to initialization interface.

Here, void destroy() method is the one which throws an exception which means above mentioned interface and bean destruction work can be carried out inside the void destroy() function as below:

public class SampleBean implements DestructableBean
{
        Public void destroysample()
        {
        //Bean Destruction Work
}
}

In case if developers are using XML configured metadata, destroy-method attribute can be used specify the method name with the signature specified as no-arguments and void return. i.e.

<bean id = “SampleBean”
        Class = “Samples.SampleBean” destroy-method = “destroysample”/>

Here is the class definition:

Following is the class definition:

public class SampleBean
{
public void destroysample()
{
// destruction work
}
}

Spring Dependency Injection

All the Java based applications (for that matter, all kinds of applications) contain few objects in tandem that work in synchronized way to present a program which an user uses as an application. However, Java developers must understand one principle is that while developing complex applications in Java, ensure to define the Java classes as much independent as possible such that they have the optimized reusability and their independent testing is possible at the time of Unit Testing. So, what helps these classes glued together is known as Dependency Injection.

Please check below class:

public class Notepad
{
        private CheckSpell checkspell;
        public notepad()
{
        Checkspell = new CheckSpell();
}
}

We are actually creating dependency of CheckSpell class inside notepad() function. Instead, something of below sort could have done our task without dependency:

public class notepad
{
private CheckSpell checkspell;
public notepad(CheckSpell checkspell)
{
  this. checkspell = checkspell;
}
  }

Here, no need for notepad to worry about the implementation of CheckSpell. In this case, SpellCheck can be implemented independently and its object will be offered to notepad during notepad initialization and entire operation will be controlled by Spring Framework. This entire approach is known as constructor based dependency injection.

Basically, control has now been removed totally form notepad and kept it in some independent entity (such as XML config file). Subsequently, dependency (class SpellCheck) is now being injected in the notepad class through the class constructor. Thus, application flow has now been inverted with the help of Dependency Injection since dependencies are now delegated to some other external method.

Another method of Dependency Injection is known as a Setter method where dependency is injected with the help of setter method of a notepad class. In this case, instance of CheckSpell class will be created and used for calling the setter method to initialize notepad’s properties.