Friday, April 30, 2010

Spring (Core, Modules, IOC, AOP)

This tutorial is prepared by various resources, link to the resources will be found at the end of article. I also tried to cover up most of the technical information of spring which can be asked during any interview. We are going to cover the aspects of Spring 3.0, along with the different modules and the framework. How to setup the spring and any type of coding stuff will not be covered in the current article, probably soon, I will have next article for spring with some of the basic coding. But the coding parts which will help to understand the flow and framework will definitely going to be covered.

What is Spring?

Spring is an open source application framework, created by Rod Johnson, can be used for Java platform as well as for .NET platform. The framework was first released under Apache 2.0 license in June 2003. The first milestone release, 1.0 was released in March 2004, and the current version is 3.0.2. One of the major advantages of the spring framework is its layered architecture, which allows being selective about the components you use, for any application development. Spring 3.0 Framework has been released with major enhancement and support for java 5.

Spring makes it possible to use plain vanilla JavaBeans to archive things that are previously only possible with EJB’s. “Spring is a lightweight dependency injection, and aspect oriented container and framework”. To make the more sense to spring, let’s break the description down:

· Lightweight: - Spring is lightweight when it comes to size and transparency. The basic version of spring is about 1MB, and processing overhead is also negligible.

· Dependency Injection: - Spring promotes loose coupling thru a technique called dependency injection (DI). When DI is applied, object gives their dependencies instead of creating or looking for dependent object.

· Aspect oriented: - APO enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do – perform business logic – and nothing more. They are not responsible for other system concern such as logging or transactional support.

· Container: - Spring container, contains and manages the life cycle and configuration of application objects

· Framework: - Spring makes it possible to configure and compose complex applications from simpler components. Spring application objects are composed declaratively, typically in an XML file.

Spring modules: -

The spring framework is made up of several well-defined modules. When taken as a whole, these modules give you everything you need to develop enterprise-ready applications.


The Core Container: - Spring’s core container provides the fundamental functionality of Spring framework. This module contains the BeanFactory which is the fundamental spring container and basis on which Spring’s DI use.

Application Context Module: - Spring Application Context builds on the core container. The core module’s BeanFactory makes spring a container, but context module is what makes it a framework. This module extends the concept of BeanFactory, adding support for internationalization (I18N) messages, application lifecycle event and validations.

Spring AOP module: - AOP is a programming paradigm in which secondary or supporting functions are isolated from the main program’s business logic. The Spring AOP module provides transaction management service for objects in the String- based application. With Spring AOP you can incorporate declarative transaction management into your application without relying on EJB Components.

Spring DAO: - The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error message thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connection.

Spring ORM: - Spring’s ORM support builds on the DAO support, providing a convenient way to build the DAOs for several ORM solutions. It doesn’t attempt to implement its own ORM solution, but does provides hooks into several popular ORM frameworks, including hibernate, Java Persistent API, Java Data Object, and iBATIS SQL Maps.

Spring MVC framework: - java has no shortage of MVC frameworks, with Apache Struts, JSF, WebWork, and Tapestry among the most popular MVC choices. Even thought Spring integrates with several popular MVC frameworks, it also comes with its own very capable MVC framework that promotes Spring’s loosely coupled technique in web layer of an application.

Spring Web module: - Spring MVC and Spring Portlet MVC requires special consideration when loading the spring application context. Therefore, spring’s web module provides special support classes for spring MVC and Spring Portlet MVC. The module also contains support for several web oriented tasks, such as multipart file uploads and programmatic binding of request parameters to your business objects.

Inversion of Control (IoC): -

IoC is an abstract principle describing an aspect of some software architecture designs In which the flow of control of a system is inverted in comparison to procedural programming. In traditional programming the flow is controlled by a central piece of code. Using Inversion of Control this central control as a design principle is left behind. Although the caller will eventually get its answer, how and when is out of control of the caller. It is the callee who decides how and when to answer.

In java there are six basic techniques to implement Inversion of Control. These are

· Using a factory pattern

· Using a service locator

· Using a constructor injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.

· Using a setter injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).

· Using an interface injection (e.g. Avalon): Injection is done through an interface.

· Using a contextualized lookdown

The basic concept of inversion of control pattern is that you do not create your objects, but describes how they should be created. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Note: Spring supports only Constructor and Setter Injection.

Benefits of IoC: -

· Minimizes the amount of code n your application.

· Managing Dependencies: - It helps in externalizing dependencies to have a centralized control over them. Dependencies can be managed at single place.

· Improved Testability: - Another reason for preferring dependency injection is that it makes testing easier. To do testing, you need to easily replace real service implementation with stubs or mocks.

· The testing problems are intensive by component environment that are very intrusive, such as Java’s EJB framework.

Spring Setter Injection: -

Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.


The setter method of property name “company” from Employee get invoked and the default value of field “company” for every new employee get set to “ABCD Company”.

Constructor Injection: -

Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. If Employee has a parameterized constructor, having ONLY company name, then the company name is injected thru constructor injection as “ABCD Company”.


Aspect Oriented Programming (AOP)

Although DI makes it possible to tie software components together loosely, aspect-oriented programming enables you to capture functionality that is used through-out your application in reusable components. Aspect Oriented Programming (AOP) complements Object Orient Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is class, whereas in AOP the unit of modularity is aspect. AOP consists of several concepts:

Consider the example: Let’s declare an interface:

public interface Foo {

Foo getFoo(String fooName,int age);

void getAfter();

void getBefore(String myName);

}

A class implementing the interface:

public class DefaultFooService implements FooService {

public Foo getFoo(String name, int age) {

return new Foo(name, age);

}

public void getAfter() {}

public void getBefore(String myName) {}

}

Till here we have simple java implementation. Now let see come AOP concepts in picture.

Before - Now I want that before the getBefore() method is called I want to log message saying what is the parameter passed.

After - Also I want that once any method in the interface is called a message should be logged after it.
I have a class which will be called to satisfy the above criteria.

public class SimpleProfiler {

public void afterMethod() throws Throwable {

System.out.println(“After the method call”);

}

public void beforeMethod(String myName){

System.out.println(“My name is “+myName);

}

}

The afterMethod() will log message after any method is called and beforeMethod() will log message before getBefore() is called. To configure this we will used xml. This is how I configure my spring.xml.

1 <'beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xmlns:aop=“http://www.springframework.org/schema/aop”

xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd”>

2 <'!– this is the object that will be proxied by Spring’s AOP infrastructure –>

3 <'bean id=“fooService” class=“DefaultFooService”/>

4 <'!– this is the actual advice itself –>

5 <'bean id=“profiler” class=“SimpleProfiler”/>

6 <'aop:config>

7 <'aop:aspect ref=”profiler”>

8 <'aop:pointcut id=“aopafterMethod” expression=“execution(* FooService.*(..))”/>

9 <'aop:after pointcut-ref=“aopafterMethod” method=“afterMethod”/>

10 <'aop:pointcut id=“aopBefore” expression=“execution(*

FooService.getBefore(String)) and args(myName)”/>

11 <'aop:before pointcut-ref=“aopBefore” method=“beforeMethod”/>

12 <'/aop:aspect>

13 <'/aop:config>

14 <'/beans>


Let see how we have configure the AOP.

Line 3 is used to create a proxy AOP object.

Line 5 we define the aspect “SimpleProfiler” class which will come into picture at different point-cuts.

Line 6 is used to configure the AOP.

Line 8-9 defines a pointcut in which an expression needs to mention. In this case the expressions say that “call afterMethod of SimpleProfiler class for any method declared inside the FooService interface.

Note Line 8-9 doesn’t define when to call afterMethod().This is done in line 9.

Line 9 states that call afterMethod() for id aopAfterMethod

Similarly for beforeMethod we define in Line 10,11.

In above example we have

Aspect : - SimpleProfiler.class
Point-cut: - aopafterMethod,aopBefore
Advice: - <'aop:before>

Now I am ready to run main class and class methods of FooService.

public class Boo {

public static void main(final String[] args) throws Exception {

BeanFactory ctx = new ClassPathXmlApplicationContext("spring.xml");

FooService foo = (FooService) ctx.getBean("fooService");

foo.getFoo("Bingo", 12);

foo.getAfter();

foo.getBefore("Himanshu");

}
}

Output is:
After the method call ( log messagefor getAfter method )
My name is Himanshu (log message for getBefore)
After the method call (log message for getAfter method)

My next blog (Spring -part2) is for Spring transaction Management and Spring Security features which is in progress and published soon. Then i will cover Spring MVC in last section (Spring part-3).


Link of resources

http://en.wikipedia.org/wiki/Spring_Framework#cite_note-3

http://tinyurl.com/zcki5l