Types of Spring Controllers

As we know that Spring has varieties of module and Model-View-Controller is one of the famous module among them, which facilitate web applications to be perform request-response over network, Now here we will learn about the controller part of MVC Framework.

We have varieties of controller to perform varieties in functionalities for which an MVC framework is responsible:

  1. Controller
  2. MultiActionController
  3. ThrowawayController 
  4. AbstractWizardFormController
  5. AbstractController
  6. AbstractFormController
  7. AbstractUrlViewController
  8. AnimationController
  9. BaseCommandController
  10. CancellableController
  11. SimpleFormController

Learning more by reading about each controller in details... follow me to learn more.

Spring Framework Brief

Spring framework makes developing enterprise application easier and simple to code, now days Spring working in full swing and now each java application demand Spring. Lets discuss the life of developers without the Spring Framework then will jump into Spring so that we can easily understand the difference and benefit of Spring in an application.

Life without Spring
- I will take my own example, when I was working on my first application for enterprise application, I have to create a component for my application which will be performing the customer management, at that time EJB was on boom, so I have chosen EJB to create this component, to start I have created several classes like Home interface, local interface and bean, additionally i have to create deployment descriptor for the bean created. Now I was afraid since 20+ number of component were still need to be created, so after analyzing and research I got to know about the XDoclet, which helps me in creating my component's supporting files with some clicks. it would feel like very easy and comfortable to build application.

Now, I have to look into the component's business logic. After implementing the business logic in component, I was looking to test my logic, I was run the container and verify the test case, but fail to verify due to some issue in code, I change it and again i have to deploy the code and run container again, after so many iterations I felt another problem in our software creation cycle with EJB. Some how I manage to test the all scenarios for the applications and successfully delivered it on time, with so much effort and problems.
I used to compile all my mistakes and problem  faced during the development of application after application delivered. Please see below what I have written:
  1. Discomfort in creating Component's Multiple supporting files
  2. Testing Slow, Re-starting the Container.
EJB, why to use EJB, only and only service it provide. Otherwise its really very painful to create multiple files. I was so much afraid that I swear not to use EJB in my future application creation, but I was not alone to decide which technology needs to be used, else I was not gonna use it again.

How Spring help?
- Spring helps developer to minimize the effort of creating the an enterprise application, which EJB doesn't provide the service to developer.  So Spring strives to be deliver the best services to developer which makes Spring developers favorite and simplifying the development model of creating an J2EE enterprise application.
Spring is helping to developer with the given below philosophy:
  1. Designing of an application is more important then underlying technology used.
  2. Loosely coupled design with Interface is a good model.
  3. Code should be easy to test.
What is Spring?
- Spring is an open source framework, written by Rod Jhonson and explain the framework in his book
"Expert One-on-One: J2EE Design and development". According to Jonson, Spring is created to address to handle the complexity of application.

Spring is a light-weight IOC and AOP container framewok. Now we will check what exactly Spring gonna do to make developer's life easy, Spring can be characterized into 5 as below:
  1. Light-weight
  2. IOC(Inversion of Control)
  3. Aspect Oriented Programming
  4. Container
  5. Framework.
Light-weight, Spring is a Light-weight framework in both terms either Size or Overhead. an average full application can be consolidated in an single JAR of 1 Mb, Spring has negligible overhead, since it is much loosely coupled with the implementation of IOC concept.

IOC(Inversion of Control), Spring promotes loos coupling between elements through a well known technique of IOC, by applying IOC in Spring Object passively given their dependency rather than creating dependent objects. It works like reverse-JNDI, instead of an object looking up dependencies through container, container provide the dependency to the objects.

Aspect Oriented Programming, This is concept introduced in Spring which separate application's Business logic with other system related codes(like Transaction, Exception handling and Audit trails) which was applied with business logic till now.

Container, Spring handle and control the objects life cycle, which makes it work like container.

Framework, Spring makes it possible to configure and compose complex application from simpler components. In spring, application objects are composed decoratively, typically in an XML file.

Now Lets talk about Spring Modules, there are below types of modules in Spring:

  1. AOP
  2. O/R Mapping
  3. JDBC and DAO
  4. Web Context and Utility
  5. Application Context
  6. Model-View-Controller Framework
  7. Core Container and Supporting Utilities
Please click here to learn spring with example, before switching to example please know how to configure your Spring 3.0 with eclipse

Must Read Articles:
We frequently update my articles to best of my knowledge, please touch base with us to get maximum.
If you like reading Please share with others or provide feedback to make it better. 

Bhanu Pratap

Spring first HelloWorld example

Here I will try to walk through the Spring3.0 first example, which will help you in understanding the spring workflow. and classes and xml required to complete one request process, here we will work on sample java application and not a web application.

Here we are creating following components to run Spring java application, but before starting please read through the configuration required for Spring3, this will help you setup spring in eclipse.

Lets create a simple class with sayHello method in it, and put some instructions so that you can see something happening in console here I have put SOP which will print a line Hello from Spring 3.0.


package com.tekhnologia.spring3.example1;
public class Spring3HelloWorld {
public void sayHello(){
System.out.println("Hello from Spring 3.0");

Spring use IOC(Inversion of Control) to create object of any class, so we have to put entry into xml file called SpringHelloWorld.xml, not required to be same as above class.
Here we are creating bean tag and putting id as a name which will be used and known to class which will be going to use the object of the above bean class. and class attribute will have full path of class going to be initialized. 

As IOC is stated for dependeancy injection which means you are not creating dependency but container is doing on behalf of you, here is the example of doing that, here we container is creating runtime  dependency by loading below xml file where ever class object is required.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="Spring3HelloWorldBean"
class="com.tekhnologia.spring3.example1.Spring3HelloWorld" /></beans>

After creating xml in which dependency is declared, we are going to use above xml to create object of bean class at step 1. We will use XmlBeanFactory to create instance for resource which will take ClassPathResource as parameter which will SpringHelloWorld.xml and now you can use XmlBeanFactory as below to create object of Bean class.

package com.tekhnologia.spring3.example1;
import java.util.Map;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;
public class Spring3HelloWorldTest {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource ("SpringHelloWorld.xml"));
Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory .getBean("Spring3HelloWorldBean");

Click here to learn spring with example.

Must Read Articles:
We frequently update my articles to best of my knowledge, please touch base with us to get maximum.
If you like reading Please share with others or provide feedback to make it better. 

Bhanu Pratap

Spring first time Configuration and set up IDE

We have divided Spring Configuration in below steps so please be sure these are available before jumping into Spring Example or Spring Application to work:
  1. JDK 5+
  2. Eclipse Setup.
  3. Spring 3.0 Download
  4. common-logging download
  5. Create Project and add lib in Eclipse

JDK 5+, Spring 3.0 is based upon JDK 5, so it will require to have JDK 5 or after version to build an Spring Application. if you don't have JDK, please download it from here.
Check Java Version by java -version

Eclipse Setup, Download the eclipse at http://www.eclipse.org/downloads/

Common-logging download, Spring use common logging for making logs so please download it from http://commons.apache.org/downloads/download_logging.cgi, else you will get an error like below:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
So please incorporate this jar in adding to project as below.

Spring 3.0 Download, Download  spring-framework-3.0.0.RELEASE-with-docs.zip at http://www.springsource.org/download, Extract the zip files as you would like:
Extracted Spring download /dist folder
 Create Project and add lib in Eclipse, Now create the project in eclipse by right click in Package Explorer and create a Java project;

Now click on Finish in the popup, Now create folder by right click(Project "tekhnologia") >> New >> Folder;

Copy and paste all jars, into your lib folder created above:

  1. Common-Logging Jars,
  2. Spring 3.0 jars

Click Finish. Now again right click(Project "tekhnologia") >> Properties >> Java Build Path >> Libraries >> click on Add JAR button,;

and after click Ok, screen will look like below;

Now Click Ok so that all lib files get set as java build path in project and finally screen will look like below;

Now your Spring is configure and you can use to for developing Spring Application. In case you are try to integrate it with Web Application, please use the project reference of this project in workspace with your web application .project file or you can use JAR architecture. its always a good idea to seperate your java component with web component in your application.

Please click here to learn spring with example.

Must Read Articles:
We frequently update my articles to best of my knowledge, please touch base with us to get maximum.
If you like reading Please share with others or provide feedback to make it better. 

Bhanu Pratap

Types of IOC(Inversion of Control) or DI(Dependency Injection)

There are two types of dependency injection: setter injection and constructor injection.

Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:

public class namebean {
String name;    
public void setName(String a) {
             name = a;
public String getName() {    
return name;

We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as showm below:
<bean id="bean1" class="namebean">
<property name="name" > <value>tom</value> </property>

The subelement <value> sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection. To set properties that reference other beans <ref>, subelement of <property> is used as shown below,
<bean id="bean1" class="bean1impl">
<property name="game">
<ref bean="bean2"/>
<bean id="bean2" class="bean2impl" />

Constructor injection: For constructor injection, we use constructor with parameters as shown below,

public class namebean {
String name;
public namebean(String a) {
name = a;

We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");

Here we use the <constructor-arg> element to set the the property by constructor injection as
<bean id="bean1" class="namebean">           <constructor-arg><value>My Bean Value</value></constructor-arg></bean>

IOC(Inversion of control) Vs DI(Dependency injection)

IOC and DI are one of the same thing in aspects of Spring Framework, Both are meant to be for same functionality.

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. 

Dependency Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. 

There are three common forms of dependency injection: 
1.) Setter
2.) Constructor
3.) Interface-based injection. 

Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

What is Inversion Of Control(IOC)?

Inversion of control or dependency injection (which is a specific type of IoC) is a term used to resolve object
dependencies by injecting an instantiated object to satisfy dependency as opposed to explicitly requesting an
object. So objects will not be explicitly requested but objects are provided as needed with the help of an Inversion Of Controller container (e.g. Spring etc).

This is analogous to the Hollywood principal where the servicing objects say to the requesting client code (i.e. the caller) “don’t call us, we’ll call you”. Hence it is called inversion of control.

Many of us are familiar with the software development context where client code collaborates with other dependent objects (or servicing objects) by knowing which objects to talk to, where to locate them and how to talk with them. This is achieved by embedding the code required for locating and instantiating the requested components within the client code.

Simple Code(Without IOC)

class TestSO {
  public void getSO(String Prop) {
      SoDAO dao = new  SoDAOImpl();
      List listSo = dao.find SoByProp(Prop);

called code:
interface SoDAO (){
     public abstract List findSoByProp(Prop);

interface SoDAOImpl extends SoDAO (){
   public List findSoByProp(Prop) {

This tight coupling can be resolved by applying the factory design pattern and program to interfaces not to
implementations driven development. Simplified factory class implemented with a singleton design pattern:

class SoDAOFactory {
 private static final SoDAOFactory singleton = new SoDAOFactory();
 private SoDAOFactory(){}
 public SoDAOFactory getInstance(){
 return singleton;

public SoDAO getDAO(){
   return new SoDAOImpl();

Now the caller code should be changed to:

class SoTest {
 public void getSo(String Prop) {
 SoDAO dao = SoDAOFactory.getInstance().getDAO();
 List listSo = dao.findSoByProp(Prop);

But the factory design pattern is still an intrusive mechanism because servicing objects need to be requested
explicitly. Also if you work with large software systems, as the system grows the number of factory classes can become quite large. All the factory classes are simple singleton classes that make use of static methods and field variables, and therefore cannot make use of inheritance. This results in same basic code structure repeated in all the factory classes.

Let us look at how dependency injection comes to our rescue. It takes the approach that clients declare their
dependency on servicing objects through a configuration file (like spring-config.xml) and some external piece of code (e.g. Spring) assumes the responsibility of locating and instantiating these servicing components and
supplying the relevant references when needed to the client code whereby acting as the factory objects. This
external piece of code is often referred to as IoC (specifically known as dependency injection) container or

Look at SpringConfig.xml file below:

<bean id="SoBean" class="SoTest" singleton="false" >
<ref bean="SoDao" />
<bean id="SoDao” class="SoDAOImpl" singleton="false" />

Now code will changes to below:

class SoTest {
   private SoDAO dao = null;
   public SoBO(SoDAO dao) {
     this.dao = dao;
    public void getSo(String prop) {
       List listSo = dao.findSoByProp(prop);

Your calling code would be (e.g. from a Web client or EJB client):

    ApplicationContext ctx = new FileSystemXmlApplicationContext("SpringConfig.xml");
    SoTest  sOo = (SoTest)ctx.getBean("SoBean");
    String prop = "beneton";

You can use IoC containers like Spring framework to inject your business objects and DAOs into your calling
classes. Dependencies can be wired by either using annotations or using XML as shown above. Tapestry 4.0
makes use of the Hivemind IoC container for injecting application state objects, pages etc.
IoC or dependency injection containers generally control creation of objects (by calling “new”) and resolve
dependencies between objects it manages. Spring framework, Pico containers, Hivemind etc are IoC containers to name a few. IoC containers support eager instantiation, which is quite useful if you want self-starting services that “come up” on their own when the server starts. They also support lazy loading, which is useful when you have many services which may only be sparsely used.

Please click here to learn spring with example.

Must Read Articles:
We frequently update my articles to best of my knowledge, please touch base with us to get maximum.
If you like reading Please share with others or provide feedback to make it better. 

Bhanu Pratap