Let’s get fancy with @Configuration with Spring

Spring has changed a lot over the years to make things more flexible and convenient for developers. Annotations in Spring 3 really hit home, but recently, Spring has added features that almost completely eliminate the need to XML all together. In the past, you still needed an XML configuration file if you wanted to utilize third-party code as Spring beans but you could use annotations to demarcate your own code. With the latest Spring code, you can use a class for your configuration. Let’s see how it works.

...
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:/app.properties")
@ImportResource("classpath:/mongo-config.xml")
public class AppConfig {

    private @Value("#{appProperties['index.location']}") String indexLocation;

    @Bean(name="indexLocation")
    public String getIndexlocation() {

         return indexLocation;

    }

  ...

//App.class main
ApplicationContext ctx =  new AnnotationConfigApplicationContext(AppConfig.class);

There is a lot going on here, but it may not be apparent by the small amount of code we have written. This code does the following:

  • Maps a class as the configuration for Spring
  • Loads an XML Property file (There are still some things I prefer to do in the XML)
  • Creates a String bean of type String and returns the definition of a property found in the Property file

While the property example is not necessarily useful in this example, you can see the flexibility of the properties using Spring expressions to access them. The first question you might ask is why am I still loading an XML file since the @Configuration annotation eliminates the need for it. If you declare a Bean in the class, you need to inject properties into it in most cases so this is a little extra work and on top of that you are writing some code that needs to be maintained. Using the XML declaration, you can use property substitution as parameters to an existing class and no code needs to be placed your configuration class.

So how do you determine when to put class in the XML and when to declare it as a bean? Here are my general rules:

  • If you create a class, the demarcate it with a Spring stereotype (@Component, @Service, @Repository, @Controller, @Configurable, etc.)
  • If the class is a class from a third-party jar, then place the configuration in the XML
  • If the class is from a third party but you want finer grain control over the events of instantiation and circumstances, then create the Bean using the @Bean annotation in the class containing the @Configuration annotation

Pretty simple rules to follow…

There are several other annotations that can be used in the class containing the configuration as well such as @Depends-On and @Value.

Java,.NET Caching with Spring

If you want a major performance boost out of your application, then caching should be a part of your strategy. No doubt you have experienced moments in coding where you needed to store sets of data so that you don’t have to go back to the source to get them every time. The simplest form of caching is lazy loading where you actually create the objects the first time in memory and from there on out, you access them from memory. In reality, caching gets a lot more difficult and has many considerations.

  • How do I cache in a distributed environment
  • How do I expire items in the cache
  • How do I prevent my cache from overrunning memory
  • How do I make my cache thread-safe and segment it

All of these are concerns that you will have if you “roll your own” solution to caching. Let’s just leave the heavy lifting to the Spring Framework and we can go back to concerning ourselves with solving the complex problems of our domain.

Spring has a caching mechanism/abstraction for both Java and .NET, although the Java version is far more robust. Caching in Spring is accomplished through AOP or Aspect Oriented Programming. A caching annotation (Java) or attribute (.NET) can be placed on a method or a class to indicate that it should be cached, which cache should be used and how long to keep the resources before eviction.

Java Spring Cache with EHCache

In Java, caching with Spring couldn’t be easier. Spring supports several different caching implementations but EHCache is the default and by far my favorite. EHCache is robust, configurable and handles a distributed environment with ease. Let’s look at how we can add the ability to cache to a Spring project.
Application-context.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:cache="http://www.springframework.org/schema/cache"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
  <cache:annotation-driven />

<!-- Ehcache library setup -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>

Now that we have our cache setup, we can start to utilize it.

@Cacheable(name="records", key="recordList") //Cache the output of records, return it if already cached
public Collection findRecords(RecordId recordId) {...}

@Cacheable(name="records", key="recordsList", condition="recordType == 2") //Only cache if record type is 2
public Collection findRecords(int recordType) {...}

@CacheEvict(value = "records", allEntries=true) //Reload the cache, evict all entries
public void loadAllRecords() {...}

In the above example, we specify through the annotation that the records collection will be stored in a cache named “records” and the key to access the collection will be called “recordList”. The key parameter is optional. We also displayed an example of using Spring Expression language to process the cache conditionally. Remember that caches are defined either dynamically like above or in the ehcache.xml. For most complex caching scenarios, you will want to define the cache in the ehcache.xml with eviction and distribution rules and Spring will find it by the name parameter in the annotation.

What about .NET?

In .NET, you have a very similar mechanism to managing a cache.

<!-- Apply aspects to DAOs -->

[CacheResult("MyCache", "'Record.RecordId=' + #id", TimeToLive = "0:1:0")]
public Collection GetRecord(long RecordId)
{
   // implementation not shown...
}

Remember that with the .NET cache, you provide the caching implementation in the XML just as you do in the Java version. In this example, we have used the provided AspNetCache.

What about controlling the cache yourself, querying the cache and more complex operations? Well even that is simple by merely autowiring the cache class or retrieving it from the context.

@Autowired
EhcacheCacheManager cacheManager;

...
EHCache cache = cacheManager.getCache("records");
Collection records = cache.get("recordList");

Built-in .NET Caching

Fortunately for .NET users, there is also a built in caching framework already in .NET. This technique is used mostly in the MVC and ASP world and I am not particularly fond of it since it is specifically geared for the web side of an application. I would prefer it to be more generic like the Spring solution, but it also has some advantages such as you can configure the caches in the web.config, you can also create custom caching implementations that utilize different mechanisms for cache management. Here is a great example utilizing MongoDB. The .NET version of the cache works much the same way as the Spring one does. Here are some examples with configuration.

[OutputCache(CacheProfile="RecordList", Duration=20, VaryByParam="recordType")]
Public ActionResult GetRecordList(string recordType) {

}

Now the configuration in the web.config…

 
//web.config

  <caching>
      <outputCacheSetting>
        <outputCacheProfile>
          <add name="RecordList"  duration="3600" />
         </outputCacheProfile>
      </outputCacheSetting>
      </caching>

If we are deploying our application to the cloud in Azure, we can use the AppFabric cache as demonstrated here.

Hibernate, Data Nucleus, JPA Result Caching

Another thing to keep in mind is that when you are using tools such as Hibernate, caching is built in with these solutions. There is a built-in second level cache implementation that is provided when you configure Hibernate and I tend to use EHCache for this as well. You must remember to add the Hibernate Cache annotation onto your objects at the class level that you want to cache as well. A properly setup ORM solution with Spring and Hibernate with a properly configured second-level cache is very hard to beat in performance and maintainability.

Conclusion

We have really done a lot with very little thanks to Spring and caching. While caching is powerful and will help improve the performance of your application, if it is overdone, it can cause problems that are difficult to diagnose. If you are caching, make sure you always understand the implications of the data and what will happen throughout the caches lifecycle.

If you are using Java, you should be using Spring

I spend a fair amount of time evangelizing the Spring Framework, and with good reason. Spring is not only a great lightweight container framework that provides IoC (Inversion of Control) and Dependency Injection, but it pretty much has a tool, component for every task that you can think of when dealing with the day to day ins and outs of programming.

You probably have a need for Spring and you don’t even know it if you haven’t used it before. Most developers at one time or another have created frameworks to accomplish tasks like remoting, JMS, MVC, database interactions, batch work, etc., so I would label Spring as “The framework” for such tasks instead of succumbing to the “roll your own” urge. I started using Spring back in 2006 and I have not, in over 50 Java projects since then, neglected to utilize it to some extent. It has reduced the amount of code I have to write, allowed me to dynamically wire dependencies together at runtime and even provided tools for tasks that I thought I was going to have to write something custom to accomplish.

Spring was born as a solution to the heavy-weight EJB and J2EE container environments. It reduces the overhead of J2EE, allows the usage of containers that are not J2EE compliant like Tomcat and Jetty and provides a consistent API that most developers these days are familiar with. Here are some example of what Spring can do:

  • Dependency Injection (e.g. create a database pool object factory in XML and inject that into objects at runtime)
  • Eliminates the need to write specific code for singleton patterns
  • Allows you to turn a POJO into a service with a mere annotation
  • With Aspects, it allows you to inject values into classes that are not managed by Spring
  • Spring has an abstraction on top of over 100 different frameworks in Java
  • Spring MVC is the most concise and robust MVC framework
  • Spring provides JPA, Hibernate and DataNucleus support and will allow transaction demarkation
  • Spring provides AOP capabilities to allow method interception and point cuts
  • Exposing POJO methods as web services is as simple as adding Apache CXF to the mix
  • Annotation support is richer than any other framework
  • Spring is the most widely used Java framework
  • Property file loading and substitution in XML

Spring is not only a Java tool, in fact, Spring.NET is available for the .NET platform. It is usually a little bit behind the Java version but it is out there.

What are these new concepts AOP, IoC and Dependency Injection?

Usually a discussion of Spring always amounts to explaining the concepts that are at the core of the framework. Let’s take a look at each of them and what they give you. IoC and Dependency Injection go hand in hand. IoC is the concept and Dependency Injection is the mechanism. For example, you create a service class on your own and now you need to manage that class by ensuring it only has one instance, you also need to get that class reference to other classes to utilize so you create a mechanism for that. Now you need transaction support so you write that in, but you also need to dynamically read in properties that are for the environment you are running in and it goes on and on. As you can see, it not only gets complicated, but that is a lot of code you are writing and maintaining yourself. Spring provides it all and through XML or annotations (preferrable the latter), you can with one simple Plain Old Java Object (POJO) accomplish all of this through Spring conventions and inject the values of the objects into your service or inject your service into any other class by simply this.


//Service class Spring Bean
@Service
@Transactional
public MyService implements IService {

public void doThis();

}

//MVC Controller Class

@Controller
public MyController {

@Autowired
MyService myService

public Report doThat() {

myService.doThat();

}

}

In just a few lines of code, we created a singleton service that is transactional and we created a controller to call that service. There are way more complex things we could do here. For example, using the OpenSessionInView Pattern, we could get the Controller to control opening the transaction and closing it to allow for multiple service calls to use the same transactional context. We could also change the isolation level of the transaction. The point here is that we used Dependency Injection to demonstrate what IoC can do.

AOP or Aspect Oriented Programming is an advanced concept in the Spring world. AOP is merely the separation of cross-cutting concerns. The Transactional support of Spring is similar to AOP. The ability of Spring and AspectJ to allow you to inject objects into other objects that are not managed by Spring is another great example. Transactions, Security, Logging and anything other than the business at hand is a cross cutting concern. The goal of AOP is to separate those away from the code. If you didn’t use AOP, then you would have to actually control these elements your self. Take for example that you want to check that a user is valid before method calls. Without AOP, you would have to write some checkUserIsValid() method and call it at the beginning of each method. Using AOP, you could merely mark with an annotation or Aspects that each method of a certain class call another method on another class as an interceptor.

Spring is also for simple projects

You may be thinking Spring is too heavy weight for the task at hand… nonsense. I will guarantee that Spring, used properly, will reduce the amount of code in your project by at least 25%. That is 25% less code for your to maintain or write in the first place. Also, Spring provides even tools to accomplish the small tasks such as the following:

  • Finding resources on the classpath or file system (ResourceLocator)
  • Finding classes with a certain annotation
  • Generating JSON/XML from objects and vice versa (Jackson support)
  • load multiple property files and substitute variables inside of your spring XML files (Useful when promoting to different environments)
  • Ability to treat a JNDI resource as just another bean
  • Ability to treat a web service as just another bean
  • JDBCTemplate for issuing database queries and batch framework for batch operations
  • Spring Data for NOSQL support with Mongo
  • MVC Content negotiation to convert a POJO to JSON,XML, PDF (iText), Excel (POI) and more
  • Security integration that supports Windows, Active Directory, Kerberos, Basic, Digest, etc.
  • Robust Testing adapters for Junit and TestNG

I could spent a week delivering Spring training to a group of developers and only scratch the surface of what is there. Without a doubt though, when I have a tough problem to solve or a simple Java project, I always utilize parts of Spring. Conveniently, Spring is broken up into modules so that you can only include the ones that have the functionality you need to avoid causing any project bloat.

Conclusion

With Spring being the #1 Java framework, I highly recommend spending some time getting familiar with it and I recommend getting some training as well from someone like myself who is an expert with the framework who can show you everything it has to offer before you start utilizing it. You can also get training directly from vmWare, the company that owns SpringSource.

Yet Another Expression Language… Spring EL

Most of the time when I hear that the term expression language I cringe, after all, we have seen so many…JSTL, JSFEL, etc and some others that will remain nameless. When I heard Spring was adding an expression language to Spring 3, I was a big dissappointed, but really I was sort of already using it and didn’t even know it with Spring Security to define my roles and accessbility rules. So I got over my dread and I took a dive into Spring EL to see how it could help make my code better.

Right off the bat, I can tell you that Spring EL will save you some coding. It gives you the ability to dynamically assign values to elements at runtime so that you aren’t stuck with a constant that you have to replace later and you won’t have to write a custom strategy class to manipulate values upon certain conditions.

Let’s look at an example I pulled straight from the Spring documentation.

...
public class MovieRecommender {

private String defaultLocale;

private CustomerPreferenceDao customerPreferenceDao;

@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
@Value("#{systemProperties['user.country']}"}

String defaultLocale) {
this.customerPreferenceDao = customerPreferenceDao;
this.defaultLocale = defaultLocale;
}

// ...
}
...

If you know anything about me, it’s that I embraced convention-based configuration and I intend to largely ignore the old XML style of defining beans. In this example, we see that the value of the user’s country is injected into the defaultLocale when the method is called.

...
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);
...

This is an example I have used before. Using Spring Security, you can define what permissions a user much have to access certain urls in your application or secure a method. 


You can pretty much use Spring EL anywhere you would have normally put a literal in an XML file, annotation value and you can even evaluate expression directly in code. If you literally want a literal just enclose your value in single ticks like ‘Hello World’.

...
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("put your expression here");
...
If you're not in a context where expressions are directly supported, you need to define your expressions 
using the JSF style #{} to get Spring to understand that you don't want a literal. 

Here is another useful example you might want to emulate. 

The calculation of the random number injected into NumberGuess is done at runtime by the expression. Normally, I would have done this by declaring another Spring Bean that is an instance of a generator and just injected that into the other class and have a method that calls the generation, but this is just much simpler.

One of my favorite points, is that you can use the Elvis operator to shorten the ternary operator syntax and not have to repeat a variable. It saves typing and since it already exists in Groovy, most will be familiar with it.

...

ExpressionParser parser = new SpelExpressionParser();
String name = parser.parseExpression("null?:'Unknown'").getValue(String.class);

...

As with anything resembling scripting or an expression language, I recommend that you use this feature sparingly. Don’t go off and litter your code with it. As a general rule of thumb, use this as a last resort for the specific circumstance where it just seems to be begging for it.

Check out the reference documentation and see how this powerful feature can help you in your coding.

Struts 2 isn’t Spring 3 but its darn close

By Chris L Hardin
Sr. Software Architect

Five years ago I wrote off Struts in favor of Spring MVC and with good reason. I was already using Spring for a myriad of other things and it was just logical to use the MVC portion since it had all the niceties that I came to expect from Struts, plus a lot more. Also, after Spring 3 came along, I think I decided there couldn’t be anything farther from perfection.

I started using Struts when it was still in its infancy and I used it on more than 20 projects, some of which were really high profile like the Toyota and Lexus Web sites. Struts was the solution to all these home-rolled frameworks that other architects were writing at the time. I think at this point all of those in-house solutions have been replaced by some Web framework by now or at least I hope they are.

I enjoyed Struts while it was in its heyday and I still think it dominates as the most widely used and accepted framework even today. All this being said, I haven’t seen anything Struts can do that can top Spring 3 though.

Recently, I had the pleasure of working on a project that was full-blown Struts 2 and I kept saying things like, “This is a new project, why are we using Struts.” and “Struts is dead…move on.” I was wrong.

Struts 2, which is actually WebWork rebranded as Struts, is a different animal. A pretty well designed framework that does a good job of creating a MVC architecture. It has all the features you have come to expect from Struts, along with a plugin framework and much, much more.

Struts 2 is still configuration heavy and I am pretty disappointed in that, but there is a convention plugin that allows you to use annotations and there is a JSON plugin as well that is really useful. All in all, I think there are around 30 plugins or more in Struts 2 that you can use.

Since I really love Spring 3 and conventional configuration options, I decided I would share some of my Struts 2 + Convention plugin configurations and code.

Simply, the convention plugin annotations allow you to use the “Zero Configuration” option for Struts 2, which I highly recommend. If you are still gluing your actions together with the struts.xml, you really need to stop overworking yourself. Let’s look at some examples of creating actions by convention.

The app that follows is an app for searching up and displaying users using either Ajax forms or an HTML form. The options you have are to return another page or just to return the JSON data.

I only have one class for this example and here is the declaration.


@ParentPackage("json-default")
@Namespace("/")
public class DefaultAction extends ActionSupport implements
ModelDriven {

Our UserSearch object contains just setters and getters for your form like get/setFirstName, etc. The UserSearch object is also annotated using the Java Validation Framework annotations. We implement ModelDriven so that we can externalize our form bean properties away from our action. We also extend ActionSupport so that we can add error and validation messages. I do not like having to extend ActionSupport just for the sake of adding messages because my object is no longer a POJO at that point. I couldn’t find anyway to add messages without extending this class.


@Action(value = "Start", results = { @Result(name = "success", location = "start.jsp") })
@Override
public String execute() {
...

private UserSearch search = new UserSearch();

@Override
public UserSearch getModel() {

return search;

}

Our first action is simple. Someone asks for /Start and we execute and redirect to start.jsp if success is returned.


@Action(value = "Process", results = { @Result(name = "success", location = "start.jsp") })
public String process() {

Set<ConstraintViolation> violations = search
.validate(search);
for (ConstraintViolation violation : violations) {
addActionError(violation.getPropertyPath() + " "
+ violation.getMessage());
}

In our form, we submit to /Process and since we have annotated the UserSearch with the Java Validation Framework, we can now validate the object. Struts 2 has built-in validation,. but I prefer to use the Java standard. If there are any constraint violations, we add them to action messages and they get returned to the client to display in the JSP page if you are using the correct tags from Struts.


@Action(value = "json", results = { @Result(name = "success", type = "json"),
@Result(name = "error",location = "start.jsp") })
public String executeAsJSON() {

Just in case you wanted to return the results of the search as JSON, you can do this in Struts 2. This will return the Model represented as JSON. This doesn’t do you much good in this case because the model is what we passed in the form, a UserSearch object. I got around this by putting a new property on UserSearch called UserSearchResult which contains the results of the search. In the executeAsJSON method, I merely call getModel().setUserSearchResult(result) and then I can access the results in JSON. In Spring 3, I could have set the return type of the method to UserSearchResult and solved the problem, but I couldn’t figure out in Struts how to do this or I don’t know if it is even possible yet, so I settled for my little hack.

I know I said that there was nothing in the struts.xml, but I didn’t exactly tell the truth. I did set some configuration options in the file.

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<!---->

<!-- -->

<!-- -->

<!-- -->
<!-- -->
<!-- -->
<!-- -->

<!-- -->

<!---->

I’m not going to go into an explanation of these properties. They are kind of self explanatory anyway.

There is also another great plugin for Struts 2 for Spring integration. It allows you to use @Autowire in your actions to automatically inject the value of a bean from Spring into the action. This is very useful, but if you’re already using Spring, you’ll probably use the more flexible Spring 3 features instead of Struts anyway.

I have to say that I love Struts 2 and you really can’t go wrong by choosing it for your MVC framework. I will add though that some more work needs to be done on supporting the convention-based options. Some of the things I would like to see are the ability to easily just let the return type be anything and have the framework convert it to JSON and I’d like to see content negotiation whereby I can change the output of the method from json to XML to PDF to Excel, just by requesting a different extension.

All in all Struts may be an old dog, but it certainly has learned some new tricks.

Caching Java methods with Spring 3

A while back I wrote about caching Java methods using an earlier version of Spring, but now I am pleased to announce that you can cache your methods using annotations with Spring 3 using Ehcache annotations for Spring.

Similar to my other post you can cache a Java method in a Spring bean by simply adding the annotation.

@Cacheable(cacheName=”dogCache”)
public Collection getDogs() throws Exception {

I really put this annotation to work in my latest project because I called many Web Services in my code that return very static data that is managed by our Enterprise Service Bus. There isn’t any need to go get the data every time since it hardly ever changes.

Using the annotation, I specify that the cache region I want to use is dogCache from the ehcache.xml file and I have it configured specific to have it handle caching dogs exactly like I want it to, even to overflow to disk if necessary. Now let’s look at the configuration necessary.

You will need to drip the jar file for ehcache-annotations in your WEB-INF/lib and then make the following modifications to your applicationContext.xml.

classpath:ehcache-spring.xml

And that’s it, you are now caching your results. Be very cautious with using this, each and every method that gets cached must be thoroughly thought through. For example, I accidentally placed this annotation on a method that returned domain objects that were already configured to be cached via Hibernate, thus doubling the amount of memory that the server was using for each object loaded.

While a very powerful tool that can increase performance, caching can also decrease it.

Spring – Caching Java methods

Caching has become an increasing concern for developers wanting to increase performance but still utilize the flexibility of Web services in their applications. There is no doubt that Web Services are extremely versatile, but the HTTP protocol combined with the marshalling and unmarshalling of SOAP, assuming you aren’t using a REST web service, is very slow and doesn’t perform very well.

The answer for most of this has come in the form of caching. I have used EHCache, my favorite open source Java caching framework on several projects in the past 3 years and I’ve used it in many different ways to increase the performance and response times of Ajax applications. Using a cache is not for the inexperienced. You can easily go overboard and degrade performance by utizing too much memory. Deciding what to and what not to cache should be a decision by your entire development team and agreed upon before implementation. I do not recommend letting a single developer run wild with a cache in hand. It’s probably just as dangerous as running with scissors.

Spring has many different way to handle integration with caching frameworks, including EHCache. Hibernate also supports many caching implementations and I use those as well. For spring 2.5 and below, there is even a library that specifically gives you the ability to use special tags in your context files to handle caching of data.

In this particular example, we are going to look at how we can use Spring, AOP and EHCache to cache the returned data of a java method, so that you don’t actually have to write the code to manage storing the objects in the cache yourself.

<beans xmlns="http://www.springframework.org/schema/beans&quot;
    xmlns:context=”http://www.springframework.org/schema/context&#8221;
    xmlns:bean=”http://www.springframework.org/schema/beans&#8221;
      xmlns:p=”http://www.springframework.org/schema/p” 
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
    xmlns:aop=”http://www.springframework.org/schema/aop&#8221;
     xmlns:ehcache=”http://www.springmodules.org/schema/ehcache&#8221;
    xmlns:security=”http://www.springframework.org/schema/security&#8221;
    xmlns:tx=”http://www.springframework.org/schema/tx&#8221;
    xsi:schemaLocation=”
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-3.0.xsd
     http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd”&gt;

 <!–  this only works in Spring 2.5 currently and you need a special third-party jar as well.
 

        <ehcache:caching id="getDistributedCache"
                cacheName=”distributedCache” />

 –>

 
    classpath:ehcache-CacheService.xml
 

 
   
 
 
    org.company.cache.METHOD_CACHE
 

 
   
 

 
   
 
 
   
      .*methodOne
      .*methodTwo
   
 

 There is the configuration and now we need a class to actually do the caching work. If you noticed above you can indicate which methods in a Spring Bean get cached by specifying a regular expression matching pattern. So for example, you could have a service class that returns a User (getCachedUser) and in your configuration .*Cached.* to match any spring bean with any method with Cached in it’s name.

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

    public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean {
      private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);

      private Cache cache;

      /**
       * sets cache name to be used
       */
      public void setCache(Cache cache) {
        this.cache = cache;
      }

      /**
       * Checks if required attributes are provided.
       */
      public void afterPropertiesSet() throws Exception {
        Assert.notNull(cache, “A cache is required. Use setCache(Cache) to provide one.”);
      }

      /**
       * main method
       * caches method result if method is configured for caching
       * method results must be serializable
       */
      public Object invoke(MethodInvocation invocation) throws Throwable {
        String targetName  = invocation.getThis().getClass().getName();
        String methodName  = invocation.getMethod().getName();
        Object[] arguments = invocation.getArguments();
        Object result;

        logger.debug(“looking for method result in cache”);
        String cacheKey = getCacheKey(targetName, methodName, arguments);
        Element element = cache.get(cacheKey);
        if (element == null) {
          //call target/sub-interceptor
          logger.debug(“calling intercepted method”);
          result = invocation.proceed();

          //cache method result
          logger.debug(“caching result”);
          element = new Element(cacheKey, (Serializable) result);
          cache.put(element);
        }
        return element.getValue();
      }

      /**
       * creates cache key: targetName.methodName.argument0.argument1…
       */
      private String getCacheKey(String targetName,
                                 String methodName,
                                 Object[] arguments) {
        StringBuffer sb = new StringBuffer();
        sb.append(targetName)
          .append(“.”).append(methodName);
        if ((arguments != null) && (arguments.length != 0)) {
          for (int i=0; i
            sb.append(“.”)
              .append(arguments[i]);
          }
        }

        return sb.toString();
      }
    }

With this example, you can see how generic you can make you caching. You may also want to tweak the ehcache settings as well. Ehcache is extremely configurable. You have many many options. Notice that above we specified a configuration file of ehcache-CacheService.xml. In this file we’ll take care of adding the caches that we want to use. Ehcache support replication via RMI, JMS and JGroups. This example replicates the cache among nodes in the cluster using RMI. Each node is discovered on it’s own so this file is the same on every server.

       
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:noNamespaceSchemaLocation=”ehcache.xsd” >

       

    
   

   
    <cacheManagerPeerProviderFactory
                        class=”net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory”
                        properties=”hostName=127.0.0.1,
                                    peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
                                    multicastGroupPort=4446, =32″/>

    <cacheManagerPeerProviderFactory
            class=”net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory”
            properties=”peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1″
            propertySeparator=”,”
            />

    

    <cacheManagerPeerListenerFactory
        class=”net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory”
        properties=”port=40001,
                    remoteObjectPort=40002,
                    socketTimeoutMillis=120000″
                    propertySeparator=”,” />

    <cacheManagerPeerListenerFactory
            class=”net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory”/>

    
    <defaultCache
            maxElementsInMemory=”1000″
            eternal=”true”
            timeToIdleSeconds=”0″
            timeToLiveSeconds=”0″
            overflowToDisk=”true”
            diskSpoolBufferSizeMB=”30″
            maxElementsOnDisk=”0″
            diskPersistent=”false”
            diskExpiryThreadIntervalSeconds=”120″
            memoryStoreEvictionPolicy=”LRU”>
               <cacheEventListenerFactory
                class=”net.sf.ehcache.distribution.RMICacheReplicatorFactory”/>
        <bootstrapCacheLoaderFactory
                class=”net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory”/>
           
            
           
           
           
     <cache name="org.company.cache.METHOD_CACHE"
           maxElementsInMemory=”10000″
           maxElementsOnDisk=”1000″
           eternal=”false”
           overflowToDisk=”true”
           diskSpoolBufferSizeMB=”20″
           timeToIdleSeconds=”300″
           timeToLiveSeconds=”600″
           memoryStoreEvictionPolicy=”LFU”>
             <cacheEventListenerFactory
                class=”net.sf.ehcache.distribution.RMICacheReplicatorFactory”/>
        <bootstrapCacheLoaderFactory
                class=”net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory”/>
           

    
     <cache name="distributedCache"
           maxElementsInMemory=”1000″
           eternal=”true”
           timeToIdleSeconds=”0″
           timeToLiveSeconds=”0″
           overflowToDisk=”true”>
        <cacheEventListenerFactory
                class=”net.sf.ehcache.distribution.RMICacheReplicatorFactory”/>
        <bootstrapCacheLoaderFactory
                class=”net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory”/>