Way2Java

Spring Framework Introduction

Spring is a light-weight IoC (Inversion of Control) Container and AOP (Aspect-oriented Programming) framework. Spring makes easier the development, testing and deployment of Java enterprise applications. Spring comes with its own MVC components that can be used in MVC Web based applications. It provides support for all Java development applications; to list a few, Hibernate, Web services, Struts, JSF (JavaServer Faces), AJAX and JPA (Java Persistence Architecture API) and other frameworks.

Light-weight container

Unlike old J2EE containers (Servlet & JSP container runs in a web server, EJB container runs in Application Server), Spring container can run on standalone JVM (no server dependencies exist to run the container). Servlet, JSP and EJB containers are heavyweight containers as they depend on underlying operating system for execution. Spring container is known as lightweight because it can run at command-prompt without depending on other containers.

Just like any other container, Spring container provides services of which two are explained below.

i) Resource Management Service

Creating and removing objects: Spring container can create single object for any number of client requests and such objects are called as Singleton. Also it can create separate objects for each client request. Such objects are called as Prototype objects.

ii) Life cycle Service

LS: LS means one method invokes after object creation and one method invokes before object destruction. Such methods are predefined in old J2EE containers such as init() and destroy() methods of Servlet. But, Spring permits to create user-defined life cycle methods that can be called in place of pre-defined life cycle methods. Just we need to mention them in Spring configuration file.

Why Spring container is called as IoC container?

In addition to providing standard container services, Spring container additionally does Dependency Injection also. Because of Dependency Injection (which is opposite principle to Dependency Lookup), it is called as IoC container. The meaning of dependency injection and its types will be known in the first program.

Spring is open-source framework developed by Rod Johnson and the latest 3.0 version was released on 23-06-2011). Spring 3.0 framework was released with major features supporting Java 5. Spring 3.0 version supports Web services. EL (Expression Language), AspectJ and Spring Object/XML mapping (oxm).

Features of Spring 3.0 Framework

Spring comes with many modules of which two are very important – Core module (provides dependency injection (IoC) and AOP module (adds extra effects like separating business logic from services).

IoC Container

The basic concept of the Inversion of Control pattern (other name, dependency injection) is that programmers don’t need to create objects but describe how they should be created. Don’t directly connect to the components and services together in code but describe which services are needed by a component in a configuration file. A container (in the case of the Spring framework, the IOC container) is responsible for all this. In IOC scenario, the container creates all the objects, connects them together by setting the necessary properties, and determines when the methods can be invoked. The implementation pattern types (dependency styles) for IOC used by Spring Framework are as follows.

  1. Dependencies can be assigned through JavaBeans properties with setter methods.
  2. Dependencies are provided as constructor parameters.

Spring philosophy is avoiding tight coupling between classes and to develop Java applications in a much simpler way (forget the annoyance of EJB complexity).

IoC (Inversion of Control)

IoC is not a new concept and exists for many years. Using object-oriented design principles and features such as interface, inheritance, and polymorphism, the IoC pattern enables better software design that facilitates reuse, loose coupling, and easy testing of software components.

Spring is developed mainly on the concept of Inversion of Control. In inversion control pattern (also familiar as dependency injection) you never create Java objects but you describe them how they should be created (or to say, how you like them created with all the data for your requirement). Which components are to be connected (or which component should be wired to another) and the services required are described in a XML file (you can call it as a configuration file). The Spring container (or to say, IOC container) is responsible to hook up all required for your job at runtime. For a practical program on IoC to understand better and easily, refer the Developing a Simple Spring Application.

Assume Class A has a relationship with Class B. It would like to use the services of Class B. The general way to put this (has-a) relationship is to instantiate Class B in Class A. Though it is alright, it establishes a ftight coupling in between the classes. It is not easily possible to change Class B without changing Class A.

To eliminate this tight coupling, you need to have a Configurator to inject the instance of Class B (Object "b") to the instance of Class A (Object "a"). If you would like to change the implementation of Class B in later stages, just simply modifiy the Configurator object. The control of getting the reference of object "b" in object "a" is inverted. Object "a" is not bothered for obtaining the reference of Object "b". It is the Configurator responsible for it. This is the basis for the IoC design pattern. Inversion of Control is all about inverting the control or how one object gets other object.

To illustrate the benefits of Configurator object, the following examples show a simple usage with and without IoC.

Note: Have some patience to go through as it is very much required to understand what IoC is.

Listing 1 and Figure 1 are simple examples in which Class A uses Class B:

public class A 
{
  private B b;

  public A() 
  {
    b = new B();
  }
}

Listing 1 assumes the following design decisions.

  1. Class A needs a reference of Class B.
  2. Class B is a concrete class that has a default constructor.
  3. Class A has an instance of class B (known as has-a relationship).
  4. No other class can access the instance of Class B.

Any of the above design decisions change, the code in Listing 1 must be altered. For example, if Class B is changed to have a non-default constructor, which takes Class C (see Figure 2), then Listing 1 would change to Listing 2.

public class A 
{
  private B b;

  public A()
  {
    C c = new C();
    B = new B(c);
  }
}

Once again, Listing 2 assumes certain design decisions. Now Object "a" owns both Object "b" and Object "c". If Class B or Class C changes, then Class A needs to change as well. Finally to say, a modest design of a very simple class with some built-in design notions becomes a terrible maintenance in the days to come; just feel it.

Other way, a framework built on IoC design pattern is used, the menace of creating Object "b" shifts from Object "a" to IoC framework and is responsible to create and place Object "b" into Object "a". IoC shields Class A from the changes made in Class B. Before an object of "a" is needed, the IoC pumps the reference of Object "b" into Object "a".

Listing 3 illustrates earlier Class A modified with IoC design pattern.

public class A 
{
  private B b;

  public A()
  {
  }
  public setB(B b) 
  {
    this.b = b;
  } 
}

Listing 3 takes the responsibility of the following policy ideas.

  1. A needs a reference to B and is not aware of how B is created and injected.
  2. B can be any Java class like a concrete class or an abstract class or an interface.
  3. Just before the object of Class A is needed, it requires a reference to the object of Class B.

From the above design ideas, you can notice that there is no tight coupling between classes A and B. Both can be changed independently without affecting the other. One point is if class B changes its methods, class A also requires to change. Object "b" creation and injection need not be known at implementation stage of object A. Here comes IoC framework. IoC make use of setB() to pump object "b" into object "a" (see figure 3).

Object dependencies uses and takes advantage of Dependency Injection (DI). DI is neat, stretchable and simple for maintenance which is very much required in large projects. Now-a-days, Spring has becomes a standard framework to use with Enterprise Applications (EA) which reduces the EA coding complexity by offering loose coupling. Module testing becomes easier with loose coupling.

More on IoC exists in the first program Developing a Simple Spring Application.

AOP (Aspect-Oriented Programming)

In computing terminology, aspect-oriented programming (AOP) is a programming style which shields supporting code (like logging etc.) from the main program’s business logic code. It’s target is to increase modularity, by permitting the separation of secondary code that cuts across the main code. The main code includes the actual business logic and the secondary code makes the business logic more robust like including the code that should be executed when a business logic fails. In AOP, this extra code is said to cross cuts the actual code.

What is concern in AOP?

Aspect-oriented programming breaks the whole logic into discrete (separate) parts known as concerns (like marketing, finance, production, planning etc). Every programming style supports these concerns by implementing them in the code thorough functions, classes, methods and modules etc. Another style of concerns exist that come across these concerns (other way which cuts across) called cross cutting concerns like logging, transaction management, security etc. AOP is an engineering discipline or engineering paradigm.

What is join point in AOP?

After knowing what a concern is, let us know what is join point. The place in the main code where the concern (code) is inserted is known as join point. The place where this extra code is inserted in the main logic is known as join point. For example, the same security check up may required to be inserted in three places in the main code, we say, there exist three join points for security permissions.

What is pointcut in AOP?

A pointcut is a set of join points or a pointcut describes the join points.

What is advice?

When the execution comes across one of the join points as said in the pointcut, a small slice of code associated with pointcut is executed. The slice of code is known advice.

What is aspect?

The programmer can describe where he requires the additional code in the main logic. The advices added are known as aspects. Aspects make clear separation between main logic and concerns.

Spring Architecture

A) The Spring framework overview

As on today, Spring is much demanded framework that reduces the complexity of developing of Java enterprise (J2EE) applications. Spring comes with 7 modules wherein Core module is the basic one. Spring adds the advantage of loose coupling to server-side Java components. Developer is allowed to use modules in his coding.

B) Brief introduction to Spring framwork modules

Among the Spring’s layered architecture of 7 modules, the Core container (module) allows the programmer to create, configure and manage the JavaBeans. Spring framework is known as lightweight container as it can be executed from the DOS prompt also without depending on the Web container (used by Servlets) or Enterprise container (used by EJBs).

1. The core container

The main classes required for IoC Spring framework exist in Core container (module). The key component in the Core container is BeanFactory. The BeanFactory belongs to Inversion of Control (IoC). IoC configures the dependency injection (DI). The DI separates the configuration from the application code.

2. Spring AOP module

The AOP module loose couples the concerns like transaction management from the main code. AOP permits to inject the aspects in the main code at different join points.

3. Spring DAO module

DAO module describes the JDBC abstraction layer. It relieves the programmer from writing tedious database specific SQL code. Lot of JDBC and concerns are written using declarative management. Declarative management avoids the traditional code with just declaring in an XML file (known as configuration file).

4. Spring ORM module
The advantage of Spring framework is it can be integrated to any ORM you like, may be popular Hibernate or others like iBATIS and JDO etc. Support to ORM along with transaction management makes Spring a much wanted enterprise framework as on today.

5. Spring Web module

The Spring Web context module provides the necessary classes required to integrate Spring with Servlets, JSP and Struts etc.

6. Spring MVC framework module

The advantages of Spring framework continues. It allows your own MVC components (like Struts) to integrate with it or use it’s built in MVC module (without the necessity of Struts). With Spring MVC module, the view need not be JSP or HTML file, it can be XSLT or Velocity templates generated view to client. Spring supports Velocity also.

7. Spring context module

Spring context is nothing but a configuration file written in XML. It gives the context information like dependency injection information, services required to run the application like validation, internationalization and JNDI etc. to the Spring framework.

Spring Containers (BeanFactory vs ApplicationContext)

Spring comes with two container interfaces – BeanFactory and ApplicationContext.

1) BeanFactory interface and its sub class XmlBeanFactory.

2) ApplicationContext interface and its sub classes FileSystemXmlApplicationContext, ClassPathXmlApplicationContext and XmlWebApplicationContext.

BeanFactory is a Lazy Bean Instantiation container.

ApplicationContext is Eager Bean Instantiation container.

In both the containers, the beans are singleton by default.

In case of BeanFactory until the getBean() method is called bean instances are not created.

In case of ApplicationContext during container start up itself all bean instances are created except prototype bean. Prototype beans are instantiated during getBean() method call.

1. BeeanFactory and XMLBeanFactory are used for standalone applications (running from some GUI like Swing GUI on client-side). These come with lazy bean instantiation container. When the client program is executed only, then bean objects are created at runtime by reading applicationContext.xml file.

2. On the contrary, ApplicationContext and its three subclasses come with eager bean instantiation container. At the server start up, applicationContext.xml file is read and objects are created. These classes are used for application servers like Web application and enterprise applications servers.

Note: Separate program (by name, BeanFactory-Singleton-Prototype) available showing clearly the difference between both the two interfaces and also singleton and prototype.

A similar explanation on Hibernate introduction is available at Hibernate Tutorial – JDBC vs Hibernate