Wednesday, October 29, 2008

Spring Framework: Spring Basics (Inversion of Control & Dependency Injection)

Before starting on with the fundamentals of Spring framework, we need to understand the term “Inversion of Control” and “Dependency Injection”.

As per Martin Fowler, “In Java community there's been a rush of lightweight containers that help to assemble components from different projects into a cohesive application. Underlying these containers is a common pattern to how they perform the wiring, a concept they refer under the very generic name - Inversion of Control”.

Inversion of Control/Dependency Injection pattern:

• Inversion of Control (IoC) container is a light weight container that helps assembling components into a cohesive application. Examples of such containers are Spring IoC Container, Pico Container etc.

• Dependency Injection (DI) pattern is a design pattern for the IoC containers for wiring components.

• In simple words, generally in Java programming we have a scenario where one object creates object instances of other dependant classes using the “new” keyword thus tightly coupling the dependant object with the actual object. To arrive at an loosely coupled model, rather than creating the dependant objects from the main object, we have assemblers/containers which assembles these dependant objects with the main object. This inverse process of creating the dependant object and injecting it to the main object is termed as DI.

• There are three different styles of DI namely Constructor Injection, Setter Injection and Interface Injection which we will discuss further in this article.

Spring: The Core Technologies:

Spring framework is an implementation of the Inversion of Control (IoC) design pattern and uses the org.springframework.beans and org.springframework.context as the core base packages. Now we will see using the two underlying interfaces as part of the above packages namely org.springframework.beans.factory.BeanFactory and org.springframework.context.ApplicationContext. They apply the Dependency Injection (DI) pattern to separate application’s configuration and dependency specification from actual code just behaving like the assembler briefed earlier.

The BeanFactory interface:

• BeanFactory interface is an implementation of factory design pattern allowing an object to be created and retrieved by name through advanced configuration mechanism.

• In short, it just instantiates and configure beans.

• It lazily loads all singleton beans. That is, it does not create bean instances when Bean Factory is created.

The ApplicationContext interface:

• ApplicationContext interface is a superset of BeanFactory that will include all functionalities that BeanFactory provides apart from other additional enterprise functionalities.

• In short, it instantiates, configures and provides supporting infrastructure to enable enterprise features like transactions, AOP, i18N, etc and is preferable over BeanFactory.

• It pre-loads all singleton beans. That is, it creates bean instances when Application Context is created.

Spring IoC Container:

• A light weight container for assembling components.

• BeanFactory and ApplicationFactory are the actual representation of the Spring IoC Container.

• In Spring context, objects (POJO) are referred as beans and are managed by the bean container also termed as IoC container. This means that IoC container provides a run-time environment for all your beans just like the Web Container providing run-time environment for all server-side scripting like Java Servlets, JSP managing its life cycle.

• Spring IoC Container manages the beans based on the bean definitions specified inside a XML based configuration metadata. This configuration file should be created by the developer and serves as a input to the container.

Instantiating the IoC Container:

IoC Container can be instantiated by creating instance of either object of type BeanFactory or ApplicationContext.

Using BeanFactory: This is the basic container for simple applications. There are several implementations of the BeanFactory, but most widely used implementation is the org.springframework.beans.factory.xml.XmlBeanFactory class which takes up object of type org.springframework.core.io.Resource. Some of the commonly used resource implementations are ByteArrayResource, ClassPathResource, FileSystemResource, InputStreamResource, PortletContextResource, ServletContextResource, UrlResource.

Using ApplicationContext: This is an advanced container and is preferred over BeanFactory. Most widely used implementation of the ApplicationContext are ClassPathXmlApplicationContext, FileSystemXmlApplicationContext.

Example#1: Instantiating a bean using Spring

Typical step-by-step example in creating a simple bean instance through Spring is as follows

• Create a simple java (bean) program.

package workspace.samples.springdemo.beancreation;

public class SimpleBean
{
public SimpleBean()
{
System.out.println("SimpleBean Instance created using Spring");
}
}

• Create a Spring configuration file.



• Create a simple client program where we instantiating the IoC Container and access the bean configured in the XML meta data file through the container

package workspace.samples.springdemo.beancreation;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class SimpleBeanClient
{
public SimpleBeanClient()
{
// To create the IoC Container using BeanFactory and retrieve bean instance from factory
BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("beanCreationContext.xml"));
SimpleBean simpleBeanObj1=(SimpleBean) beanFactory.getBean("simpleBean");

// To create the IoC Container using ApplicationContext and retrieve bean instance from context
ApplicationContext context=new ClassPathXmlApplicationContext("beanCreationContext.xml");
SimpleBean simpleBeanObj2=(SimpleBean) beanFactory.getBean("simpleBean");
}

public static void main(String args[])
{
SimpleBeanClient beanClient=new SimpleBeanClient();
}
}


Example#2: Spring DI: Setter Injection

Typical step-by-step example in injecting dependent objects through Spring DI is as follows

• Create two simple java program of which one is dependent on another.

EngineBean.java:

package workspace.samples.springdemo.beaninjection;

public class EngineBean
{
public EngineBean()
{
System.out.println("[EngineBean] [instance created]");
}
public void checkEngine()
{
System.out.println("[EngineBean] [checkEngine] ...");
}
}

CarBean.java:

package workspace.samples.springdemo.beaninjection;

public class CarBean
{
public CarBean()
{
System.out.println("[CarBean] [instance created]");
}
// This is required for the Spring Container to inject the bean EngineBean into this CarBean object
public EngineBean engineBean;
public void setEngineBean(EngineBean engineBean)
{
System.out.println("[CarBean] [EngineBean instance injected into CarBean]");
this.engineBean=engineBean;
}

public void startEngine()
{
engineBean.checkEngine();
System.out.println("[CarBean] [startEngine]...");
}
}


• Create a Spring configuration file



• Create a java client program which creates instances of the two java beans and then injects the dependent bean into the other bean through Spring DI.


package workspace.samples.springdemo.beaninjection;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class CarDriverClient
{
public CarDriverClient()
{
System.out.println("[CarDriverClient]");
// To create the IoC Container using BeanFactory and retrieve bean instance from factory
BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("carBeanInjectionContext.xml"));
CarBean carBeanObj1=(CarBean) beanFactory.getBean("carBean");
carBeanObj1.startEngine();

// To create the IoC Container using ApplicationContext and retrieve bean instance from context
ApplicationContext context=new ClassPathXmlApplicationContext("carBeanInjectionContext.xml");
CarBean carBeanObj2=(CarBean) beanFactory.getBean("carBean");
carBeanObj2.startEngine();
}
public static void main(String args[])
{
CarDriverClient carDriverClient=new CarDriverClient();
}
}

Sunday, October 12, 2008

Spring Framework: Getting Started

This is a quick introductory tutorial on getting started with Spring framework. It is intended for people setting-up the development environment with Spring framework installation and understanding the Spring distribution.

Introduction:

Please go through the quick start tutorial posted earlier to understand Spring framework and its architecture before getting started.

http://w-o-r-k-s-p-a-c-e.blogspot.com/2008/10/article-spring-framework-introduction.html

Installation of Spring framework comes up as a zip file distribution and the release information can be found under readme.txt file of the distribution. This tutorial covers the installation of Spring Framework 2.5.5 distribution that requires JDK 1.4.2 or later and J2EE 1.3. So we will use Sun JDK 1.5 with eclipse

Installation:

• Download the binary distribution from http://www.springframework.org/download
• The binary distribution of Spring framework consist of the following directory layout



• To install Spring framework, copy/extract the distribution files to a particular directory

Set Environmental Variables:

• Set JAVA_HOME environment variable to the directory where JDK is installed.
• Add Spring_Installation/dist/spring.jar to classpath.
• Add Spring_Installation/lib/jakarta-commons/commons-logging.jar to classpath.

Thursday, October 9, 2008

Spring Framework: Introduction

This is a quick introductory tutorial to the Spring framework and their Architecture. It is intended for people starting out with understanding the Spring modules.

Introduction:

• Spring is a modular Java/J2EE application framework.

• Spring is an open source light-weight framework to address the complexity of any enterprise application development.

• Spring is a well organized and layered architecture with pre-defined modules that can work independently or in combination, providing a framework for J2EE application development allowing us to use only components that are needed.

• Spring can be used with any J2EE server. Primary focus of Spring is to allow reuse of business and data access objects across J2EE environments, Standalone environments, test environments etc without being tied up with just J2EE services.

Spring Framework Architecture:

Following are the various modules of Spring Framework Architecture



Spring CORE:

• Spring Core is the core container for the entire Spring framework providing the base essential functionality features like dependency injection.

• Primary component of the core container is the “Bean Factory”, an implementation of factory pattern to instantiate bean creation. It applies the Inversion of Control (IoC) pattern to separate application’s configuration and dependency specification from actual code.

• It includes supporting utilities and bean container.

Spring CONTEXT:

• Spring Context is a configuration file providing context information to the Spring framework.

• It provides API for obtaining message resources.

• It includes enterprise services like JNDI access, i18n support, EJB integration, remodeling email, UI validation and scheduling functionality.

Spring DAO:

• Spring Data Access Object (DAO) is an abstraction layer providing meaningful exception hierarchy for managing database connection, exception handling and errors thrown by different database vendors.

• It reduces the amount of code one need to write, such as opening and closing connections.

• It includes transaction infrastructure, JDBC support and DAO support.

Spring ORM:

• Spring Object Relational Mapping (ORM) is an interfacing layer providing support for most ORM framework.

• It includes integration support for Hibernate, iBATIS SQL Maps, JDO, JPA, TopLink etc.

Spring AOP:

• Spring Aspect Oriented Programming (AOP) which is fully integrated with Spring configuration management allows to enable AOP features to any objects managed by the Spring framework and incorporates declarative transaction management into your application especially without EJB.

• It includes run time support for the cross-cutting behavior called “aspects” through its meta-data programming that adds annotations to the source code which instructs Spring in applying aspects across multiple components in a system thus complementing OOP with AOP model.

Spring WEB:

• Spring Web is built on top of the Spring Context module providing context for web based applications.

• It includes integration support with various (Model-View-Controller) MVC frameworks like Struts, JSF and web works etc.

Spring WEB MVC:

• Spring Web MVC is a full-featured MVC implementation for building web applications which is highly configurable.

• It includes support for multiple view technologies like JSP, velocity, Tiles, POI, iText etc.

Reference Links:

Spring, one of the leading platform to build and run Enterprise Java
http://www.springframework.org/

Tuesday, October 7, 2008

Quick Start Tutorial: Apache ANT

This is a quick introductory tutorial to the Ant build tool. It is intended for people starting out with Ant and Java development, and aims to provide enough detail to get started.

Introduction:

ANT (originally an acronym for Another Neat Tool) is a platform independent java based build tool written purely in java. Ant is particularly good at automating complicated repetitive tasks and thus is well suited for automating standardized build processes. Ant accepts instructions in the form of XML based documents thus are extensible and easy to maintain.

Installation:

* Download the binary distribution of Ant from http://ant.apache.org/.
* The binary distribution of Ant consists of the following directory layout.


* To install Ant, copy the distribution files to a particular directory.
* Set the ANT_HOME environment variable to the directory where ant is installed.
* Add ANT_HOME/lib/*.jar to classpath.
* Set JAVA_HOME environment variable to the directory where JDK is installed.
* Add the Ant’s bin directory to your path.

Basics: A Simple build process for Java project

Ant uses what it calls a build file to set out steps it will take. An Ant build file comes in the form of an XML document; all that is required is a simple text editor to edit the build files. The Ant installation comes with a JAXP-Compliant XML parser; this means that the installation of an external XML parser is not necessary.

Syntax: ant [options] [target [target2 [target3] …]]

Example #: Creating a COMPILE task for java

A simple example is shown below followed by a set of instructions indicating how to use Ant. This example will demonstrate on how-to write a simple build file for creating an output folder, compiling java source, and outputting the generated class files to the output folder.

Steps to build the compile ant task:

* Create similar to the below code into a file named build.xml. Create a directory and place the xml file into it.


(1) As Ant build files are XML files, the document begins with an XML declaration which specifies the version of XML in use.

(2) The root element of an Ant build file is the project element, it has three attributes. Out of these attributes, default is the only required attribute.

# name – denotes the name of the project.
# default – denotes the default target to be used when no target is specified.
# basedir – denotes the base directory of the project. By default, it denotes the parent directory of the build file.

(3) The property element allows the declaration of properties which are like user-definable variables available for use within the build file. The name attribute specifies the name of the property and value attribute specifies the value of the property. In this example, src property has a value “.” and output property has a value “build”.

In order to refer this property, specify the name of the property between ${ and }. In this example, the property src and output are later referred under target elements.

(4) The target element is used as a wrapper for a sequence of actions. A target has a name attribute so that it can be referenced from elsewhere, either externally from the command line or internally via the depends keyword, or through a direct call. It has a number of possible attributes out of which the name attribute is the only required attribute.

# name – denotes the target name which can be referenced from elsewhere.
# depends – denotes a comma separated list of all the targets on which this target depends. In other words, depends contains all the targets that must be executed prior to executing this target.
# if – allows adding conditional attribute to a target based on the value of the property.
# unless – converse of “if” attribute. That is, the targets content would be executed unless the property is set.
# description – provides a short description of the target.

In this example, the target “init” – initialize is used to create the output folder if it doesn’t exist through the mkdir element with the name specified by the output property defined earlier. The echo element is used to echo the message text to the current loggers and listeners which means System.out unless overridden. The task can also echo to a file.

(5) As explained in four, depends allows one to specify other targets that must be executed prior to the execution of this target. In this example, depends=”init” is used to indicate that the compile target requires that the target named init be executed prior to executing the body of compile.

The javac element, as used above, is a task, tasks are performed in the body of a target, in this case, the source directory is specified by referencing the src property and the destination directory is specified by referencing the output property. The example above causes javac to be executed, compiling all the .java files in the directory specified by the src property and placing the resultant .class files in the directory specified by the build property.

* Create a sample java source file and place it in the same directory as build.xml file.


* Type the command ant at the command line in the directory. This would create a directory called build under the test directory, compile the entire java source (BuildTest.java) under test directory and place the compiled class files (BuildTest.class) under the build directory that’s been created earlier.


* A nice feature of Ant is that by default, only those .java input files that have a more recent timestamp than their corresponding .class output files will be compiled.

A Typical Project: Build process of a J2EE web project

A typical J2EE web application is defined as a hierarchy of directories and files in a standard layout. Such a hierarchy can be accessed in its "unpacked" form, where each directory and file exists in the file system separately, or in a "packed" form known as a Web ARchive, or WAR file. The former format is more useful during development, while the latter is used when you distribute your application to be installed.

Example #: Using Ant to manage the J2EE web development and build process

This example will demonstrate on how-to write a build file for creating a J2EE web application.

Steps to build the web application task:

* Save the below code into a file named build.xml. Create a directory and place the xml file into it.


(1) These properties generally define the file and directory names (or paths) like application name, build directory, distribution directory, documentation directory, java source code location path, document files like html, jsp, js etc., external library path that affect where the build process stores its output.

(2) Instead of replying on the CLASSPATH environmental variable, Ant includes features that make it easier to dynamically construct the classpath for each compilation. Includes all jar files to classpath under the lib directory.

(3) The "all" target is a shortcut for running the "clean" target followed by the "compile" target, to force a complete recompile.

(4) The "clean" target deletes any previous "build" and "dist" directory, so that you can be ensured the application can be built from scratch.

(5) The "prepare" target is used to create the "build" destination directory, and copy the static contents of your web application to it.

(6) The "dist" target creates a binary distribution of your application in a directory structure ready to be archived in a war file. Note that this target depends on two others:
# "compile" so that the entire web will have been assembled
# "javadoc" so that the application Javadoc will have been created

(7) The "javadoc" target creates Javadoc API documentation for the Java classes included in your application. Normally, this is only required when preparing a distribution release, but is available as a separate target in case the developer wants to create Javadoc independently.

(8) The "prepare" target is used to create the "build" destination directory, and copy the static contents of the web application to it.

Core ANT Tasks - glimpse:

There are large numbers of tasks available with Ant; the following table will show some of the core tasks. Refer the links section to know more about other tasks.



Tips:

* Use properties – Ensures reusability of build files by using property element.
* Use relative file paths – Ensures projects portability.
* Comment Ant build files – Adding descriptions attribute to targets ensures better readability.
* Ant documentation – Ant’s documentation is a comprehensive and contains many useful examples.

Reference Links:

* Apache Ant Resource Homepage
  http://ant.apache.org/resources.html
* Apache Ant Manual
  http://ant.apache.org/manual/index.html
* Binary distribution of Apache Ant
  http://ant.apache.org/bindownload.cgi
* Complete list of Apache Ant Tasks
  http://ant.apache.org/manual/anttaskslist.html

Thursday, October 2, 2008

Tools: Build Process Management & Integration

Build tools are mainly used and very much helpful in automating the build process for developers. They automate any tasks that developer might encounter during construction, testing, or deploying software application thus saving time drastically.

Following are few good practices on build process:

* Builds should be portable across operation systems.
* Builds should be independent of any IDE.
* Builds should support for multiple tasks/activities automatically.
* Continuous Integration (CI) of build for frequent integration activities.

Few of the well-known and widely used open source tools for build process are listed below:

Apache ANT - Another Neat Tool (ANT) is a Java based build scripting tool that uses XML based build file that describes the steps to build a project. It uses task-driven approach with many built-in tasks readily available with the tool.

Reference links: http://ant.apache.org/

Apache Maven - Maven is a Java based build scripting tool that also uses XML based build file that describes the project itself in a declarative way to build a project rather on steps. It uses declarative approach where project structure and contents are described promoting the standard directory structure.

Reference links: http://maven.apache.org/

CruiseControl - CruiseControl is a open source continuous integration tool for continuous build process management that uses XML based configuration file. It uses a process on CI server that periodically checks for any updates in source code repository, runs the build process and notifies listeners (including team members) through email, RSS etc.

Reference links: http://cruisecontrol.sourceforge.net/