Thursday, October 6, 2011

Annotations in Spring

Annotation in Java and Spring has made developer’s life very easy. To use Annotation in spring we need to add following tags in Spring Configuration file


<context:component-scan base-package="com.spring.action"></context:component-scan>
By default, <context:component-scan> looks for classes that are annotated with one of a handful of special stereotype annotations:

  • @Component—A general-purpose stereotype annotation indicating that the class is a Spring component
  • @Controller—Indicates that the class defines a Spring MVC controller
  • @Repository—Indicates that the class defines a data repository
  • @Service—Indicates that the class defines a service
  • Any custom annotation that is itself annotated with @Component

Difference between @Service and @Component
They both belong to org.springframework.stereotype.Service

When annotating your class with @Component you mark it as a regular java component class when annotating with @Service you mark it as a “special” type of component for special purpose like transaction or associating with aspects.


Autowired is one of very important Annotation in spring

If we write

MyController c;

Its mean Spring will look for a class with name MyController If its an Interface then it will look for its implementer classes. If two classes have implemented this Interface and they both have @Component Annotation then Spring will generate exception

In this case you have two options

1) Option1
Give name to component like

In this case you have to define your variable like this

MyController FirstController;

MyController SecondController;

2) Option
Use Qualifier


and in your service use

MyController c;

Another Example of Autowire

package com.spring.action.controller;

import org.springframework.stereotype.Controller;

public class ThirdController implements MyController {
            public boolean processMethod(String s){
                        System.out.println("Third Controller is processing Method");
                        return true;

When Spring scans the com.spring.action package, it’ll find that ThirdController is annotated with @Controller and will automatically register it in Spring. By default, the bean’s ID will be generated by camel-casing the class name. In the case of ThirdController that means that the bean ID will be thirdController.

We can use it in any of my class by writing

MyController thirdController;

The @Inject annotation from JSR-330

In an effort to unify the programming model among the various dependency injection frameworks, the Java Community Process recently published the Dependency Injection for Java specification. Known in the Java Community Process as JSR-330 or more commonly as at inject, this specification brings a common dependency injection model to Java. As of Spring 3, Spring supports the at inject model.2 The centre piece of JSR-330 is the @Inject annotation. This annotation is an almost complete drop-in replacement for Spring’s @Autowired annotation. So, instead of using the Spring-specific @Autowired annotation, you might choose to use @Inject on the instrument property:

Instead of @Qualifier Inject is using

private Instrument instrument;

Spring 3.0 introduced @Value, a new wiring annotation that lets you wire primitive values such as int, boolean, and String using annotations.

private String song;

 Sample Project is present at following location

Tuesday, October 4, 2011

EhCache Integration with Spring and Hibernate. Step by Step Tutorial

EhCache is a very popular open source caching framework widely used for Java based Caching.

Currently it’s owned by and 2.5 beta releases is available for download.

In this article I just focused on EhCache Integration with Spring and Hibernate also I just explained few basic concepts which are required to understand Code. For detailed Caching Concepts Please visit

Cache Manager, Caches and Elements are main entities of EhCache

EhCache consists of a CacheManager, which manages Caches. Caches contain Elements, which are essentially name value pairs. Caches are physically implemented either in-memory, or on disk.

Integration with Spring

EhCache integration with Spring is quite simple. You just need to define some properties in spring configuration xml file and its ready to use. Spring is using Annotation to integrate EhCache and by this we can add caching to any method results

EhCache Annotations for Spring is available via maven, simply add the following dependency to your pom.xml  

Next Step is to perform changes in your spring Configuration file. Below is my Spring configuration file which contains EhCache configurations

Important point to note here is that Cache Manager Name and its Configuration Location. We can use cacheManager in our code to store and retrieve information from Cache.

ehcache.xml file is configuration file for EhCache where we can define configuration details of EhCache. In my case here is content of my ehcache.xml file

Here it’s clear that we have created a cache with name Customer, I will use this Cache to store Customer details

Next step is to use it in your code. In my example I created a simple Spring based application where we have Customer Controller which is used to retrieve Customer Information

We have Customer Object with Customer Id, name and address details and related setter getter methods

Next step is to create Controller. Customer Controller is very simple. I am using Spring Restful Web services to retrieve Customer Information. In my Controller I have no logic related to EhCache. I just have two versions of getCustomer method (one with Annotation and one without Annotation), save Customer and Clear Cache method. Code is simple and self explanatory for any Spring MVC developer.

If you notice Controller is calling Customer Service. Customer Service is our main class and it’s used to get Customer Information. It can get information from Database using Hibernate or from any backend. Here I just provided basic implementation. Idea is to understand usage of EhCache
Following Service methods are used to retrieve and store information in Cache

Previously we have defined “cacheManager” object in our Spring.xml file and also we have defined a Cache with name “customer” in ehcache.xml file. Its time to use both these configurations
getCache method is use to retrieve Cache Object and we are storing new Element in this cache. Element requires key, value pair so I am using id filed as a key. Later on we can use same key to retrieve Customer Object from Cache.

Another great way of using EhCache is Spring Annotation


Add Cacheable Annotation to methods you would like to cache. In our case we are using it for getCustomer method. If we call getCustomer method with customerId 1, first time complete method will be called. If we will call this method again with same customerId then response will be returned from Cache.

To Clear Cache we can just use TriggerRemove Annotation


Complete Source Code is present at following location

Integration with Hibernate as a Second Level Cache

Hibernate uses different type of Caches

·         The first cache type is the session cache. The session cache caches object within the current session.
·         The second cache type is the query Cache. The query cache is responsible for caching queries and their results.
·         The third cache type is the second level cache. The second level cache is responsible for caching objects across sessions.
EhCache is used as second level cache. EhCache integration with Hibernate is quite simple as well. You just need to define some properties in persistence.xml file.
EhCache jars are available via maven, simply add the following dependency to your pom.xml  

Next step is to perform changes in persistence.xml  


 Put ehcache.xml at your classpath. It could be in classes or WEB-INF folder


In you Entity just add Annotations related to ehcache and thats it.


Complete Source Code is present at following location