Error while running junit with Spring 3.2

My first attempt of upgrading project to use spring 3.2.0.RELEASE.

I was trying to run bunch of Junit test cases (which run fine with 2.5.6 ) , i got following error

java.lang.NoSuchFieldError: NULL


After searching google couple of suggestions people suggested

Spring 3.2 may not be compatible with old version of spring, so make sure about it.
Junit should be 4.5 + . I changed to 4.10
It didnt work then I found the class “TypeValue” is part of spring-expression jar file. So i added it explicitly with version 3.2 and it worked .

Happy Coding !!

Using Spring form to add enum values of JSP page

At times it is required to add Enum values on the jsp page so that its easy to handle on the server side. To display this feature i am using spring 3.0 version.
Lets create a Java Enum Class and override some of its behavior

public enum WorkingDay {</code>


private String description;

private WorkingDay(String description) {
this.description = description;

public String getValue() {
return name();

public void setValue(String value) {}

public String getDescription() {
return description;

public void setDescription(String description) {
this.description = description;


I just want 4 working days in a week 🙂 .

Now register a binder to the controller.

protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {</code>

binder.registerCustomEditor(WorkingDay.class, new PropertyEditorSupport() {
public void setAsText(String value) throws IllegalArgumentException {


public String getAsText() {
if(getValue() == null)
return "";

return ((WorkingDay) getValue()).name();

Set the WorkingDay object to the model object for the view. It should be in the same controller in which the above binder is registered.

@RequestMapping(value="/form", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("/view_my_jsp");
model.addObject("workingday", WorkingDay.values());
return model;

Add the code in “view_my_jsp.jsp”

<form:radiobuttons path="type" items="${workinday}" />

The value of path should match the field name of the property of the command object passed.
The jsp page will contain four radio buttons.

How to configure Hibernate in Spring.

The objective of the tutorial is to understand how the DB can be configured in Spring using Hibernate.
To start with download:
1) spring jars
2) hibernate jars
3) mysql driver

Following is the list of jars I used.

1) create a Db in mysql with name “reco_engine”;
2) Create a table User and add some columns to it.
3) Insert some records into the table using mysql..

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<bean id="hibernateDao" class="HibernateAccessDao">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/reco_engine"/>
<property name="username" value="root"/>
<property name="password" value="root"/>

<bean id="mySessionFactory"
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<property name="hibernateProperties">

<bean id="hibernateTemplate"
<property name="sessionFactory">
<ref bean="mySessionFactory"/>

The bean “datasource” is used to configure the properties of the DB.
The bean “mySessionFactory” is used to maintain the session of hibernate. This is taken care by the spring container now.
The property “mappingResources” takes the list of hbm files which will be mapped to this session. Also the datasource property is set in this bean.

The bean hibernateTemplate is the one used to interact with the DB. The Spring application context will manage its lifecycle, initializing and shutting down the factory as part of the application. LocalSessionFactoryBean is the preferred way of obtaining a reference to a specific Hibernate SessionFactory, at least in a non-EJB environment.

The bean “hibernateDao” is the java class and the hibernateTemplate property is set.

The Users table has to be mapped in Hibernate. To map it , and Users.hbm.xml need to be created . I have used the Hibernate plugin for eclipse provided by JBoss to generate the files automatically.

The files will be as follows:

public class Users  implements {

    // Fields    

     private int id;
     private String firstname;
     private String lastname;
    // Constructors

    /** default constructor */
    public Users() {

	/** minimal constructor */
    public Users(int id) { = id;
    // Property accessors

    public int getId() {
    public void setId(int id) { = id;

      public String getFirstname() {
        return this.firstname;
    public void setFirstname(String firstname) {
        this.firstname = firstname;

    public String getLastname() {
        return this.lastname;
    public void setLastname(String lastname) {
        this.lastname = lastname;

The Users.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!-- Generated Jun 3, 2010 9:15:59 PM by Hibernate Tools 3.1.0.beta4 -->
    <class name="Users" table="users" catalog="reco_engine">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        <property name="firstname" type="string">
            <column name="firstname" length="45" />
        <property name="lastname" type="string">
            <column name="lastname" length="45" />
        <property name="designation" type="string">
            <column name="designation" length="45" />
        <property name="department" type="string">
            <column name="department" length="45" />

The Dao class to interact with the database:

public class HibernateAccessDao {

	HibernateTemplate hibernateTemplate;

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context =   new ClassPathXmlApplicationContext("spring.xml");
		HibernateAccessDao dao =(HibernateAccessDao) context.getBean("hibernateDao");
// This method retrieves the record with id =1
	private void getRecords(){
		Session session = hibernateTemplate.getSessionFactory().openSession();
		Users user = (Users) session.load(Users.class, 1);


The session.load(User.class,1) will load the record of the user with id =1

VMWare acquires SpringSource

Another emerging open source company acquired. In their press release vmware announced that it had acquired SpringSource for some some reasons.

Over last 5 yrs Springsource has emerged as one of the leaders in providing framework and support to develop enterprise applications. OVer short span of time its had provided one of the stable framework for developing applications.

This news has come as a surprise at least to me and a disappointment.

More details are here VMWare acquires SpringSource

Spring AOP tutorial -I


Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects.

AOP concepts:

Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in J2EE applications. In my words: a trigger which can affect the multiple classes a one point….
Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. In my words: a locus of points where execution will happen.
Advice: action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. (Advice types are discussed below.) In my words : the action to be taken at the point.
Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default. In my words a criteria used to locate point.
Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Consider the example:

Lets 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 xmlThis is how I configure my spring.xml.

<beans xmlns=;




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

1 <bean id=“fooService” class=“DefaultFooService”/>


3 <!– this is the actual advice itself –>

4 <bean id=“profiler” class=“SimpleProfiler”/>


6 <aop:config>

7                <aop:aspect ref=”profiler”>

14 <aop:pointcut id=“aopafterMethod”

expression=“execution(* FooService.*(..))”/>

15 <aop:after pointcut-ref=“aopafterMethod”


16 <aop:pointcut id=“aopBefore”

expression=“execution(* FooService.getBefore(String)) and args(myName)”/>

17 <aop:before pointcut-ref=“aopBefore”





Let see how we have configure the AOP .

  • Line 1 is used to create a proxy AOP object..
  • Line 7 we define the aspect “SimpleProfiler” class which will come into picture at different point-cuts.
  • Line 6 is used to configure the AOP.
  • Line 14 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 14 doesn’t define when to call afterMethod().This is done in line 15
  • Line 15 states that call afterMethod() for id aopAfterMethod
  • Similarly for beforeMethod we define in Line 16,17.

    In above example we have

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

    Now I am ready to run my 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("Pengo", 12);

    OutPut is
    After the method call ( log messagefor getAfter method )
    My name is Harshit (log message for getBefore)
    After the method call (log message for getAfter method)

    How to build various pointcut expression.

    How to inject prototype dependency in a singleton bean

    As we know once the singleton bean is created all the properties object defined in it are created once. But what about special and rare case in which one of the property object needs to be created everytime the singleton object is required. for example i have put a property in a singleton object as Timestamp, which can tell me when my singleton object was accessed. For this I need to know the exact time when the object is fetched and not created.
    Possible solution could be everytime the method “getInstance()” is called a new Timestamp object is created and injected into spring object.
    This is also possible in Spring using look-up method injection.
    Lookup method injection refers to the ability of the container to override methods on container managed beans, to return the result of looking up another named bean in the container. The lookup will typically be of a prototype bean.

    public abstract class SingletonBean{
    public abstract Timestamp getCurrentTime();

    In spring.xml
    < bean id="mySingleton" class="com.SingletonBean" >
    < lookup-method name="getCurrentTime" bean="currentTimeBean"/ >
    < / bean >
    < bean id ="currentTimeBean" class="java.sql.TimeStamp" scope="prototype"/ >

    It is mandatory to make currentTimeBean as prototype otherwise same instance of bean will be passed.

    Dependency Injection in Spring

    Dependency Injection (DI): is a way to let the framework or the container work out the complexities of service instantiation, initialization and sequencing and supplies the service references to the clients as required. In spring IOC container has the responsibility of doing DI.


    Consider a simple example:


    public interface Vehicle {

                     void displayData();



    A FourWheeler class implements Vehicle interface.


    public class FourWheeler implements Vehicle {


          private String name;

          private int purchaseValue;

          private int noOfTyres;

          public FourWheeler(){}                          // default constructor                   

    public FourWheeler(String name, int purchaseValue, int noOfTyres) {


       = name;

                this.purchaseValue = purchaseValue;

                this.noOfTyres = noOfTyres;


          public void displayData() {

                System.out.println(” Name of vehicle is “+ name);

                System.out.println(“Purchase Value is “ +purchaseValue);

                System.out.println(“Tyres the vehicle has “ +noOfTyres);


          public String getName() {

                return name;


          public void setName(String name) {

       = name;


          public int getPurchaseValue() {

                return purchaseValue;


          public void setPurchaseValue(int purchaseValue) {

                this.purchaseValue = purchaseValue;


          public int getNoOfTyres() {

                return noOfTyres;


          public void setNoOfTyres(int noOfTyres) {

                this.noOfTyres = noOfTyres;




    The different ways in which the class can be instantiated using DI in spring.xml:


    1) Setter based injection: The values of the properties of the class are set with the help of setter. Each class needs to declare the setter of the properties and their values are set from the spring configuration file.


     <?xml version=“1.0” encoding=“UTF-8”?>



           <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

                <property name=“noOfTyres”> <value>4</value>



    <property name=“name” value=“Honda”/>                                  

    <property name=“purchaseValue” value=“900000”/>  




    In above example the setter methods are created for noOfTyres, name, purchaseValue in FourWheeler  class and the values are set using <property> <value> tag in xml file.

    Note that for each property the value is set using a different syntax. All syntaxes are valid and

    can be used depending on the programmer liking. In this declaration the default constructor of class is called.


    2)  Constructor Based injection: In this case the values are set using constructor of the java class. The call to constructor is made from the xml file using <constructor-arg>.  For the above mentioned java class constructor injection will be:


    <?xml version=“1.0” encoding=“UTF-8”?>


    <beans >      


          <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

                            <constructor-arg> index=“0” value=“Honda”/>

                            <constructor-arg type=“Integer”>







    In the above example the values to the bean is passed using <constructor-arg>. The sequence in which the parameters are passed should match with the constructor available in the class.


    3) Static factory method: In the less common case where the container invokes a static, factory method on a class to create the bean, the class property specifies the actual class containing the static factory method that is to be invoked to create the object (the type of the object returned from the invocation of the static factory method may be the same class or another class entirely.


    Consider the following method present in FourWheeler class:

    public static TwoWheeler createInstance(){

                return new TwoWheeler();



    Note that the method has to be static. And following line of code in xml:


    <bean id=“twoWheeler” class=“com.src.FourWheeler” factory-method=“createInstance”/>


    After execution of the above line twoWheleler bean will represent the TwoWheeler object which is created by calling the function from FourWheeler Class. The attribute factory-method tells which method to call present in the class mentioned. This scenario could possibly use in cases where Factory pattern is required.


    4) Instance Factory method: In this case instead of having a static method a non-static method is present to create the object.


    Consider the following method present in FourWheeler class:

    public TwoWheeler createInstance(){

                return new TwoWheeler();



    Note that the method need not be static. And following line of code in xml:


    <bean id=“parentfourWheeler” class=“com.src.FourWheeler”/>


    <bean id=“fourWheeler” factory-bean = “parentFourWheeler” factory-method=“createInstance” />


    Here the twoWheeler object is created from a non-static method of class FourWheeler.