Home > Java > Simple caching with Spring AOP

Simple caching with Spring AOP

It’s recommended to read Simple caching with AspectJ before you continue. Only difference is in using Spring AOP.
At first we need to create spring-config.xml and define Spring beans and enable Spring AOP autoproxy for AspectJ:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<aop:aspectj-autoproxy />
	<bean class="caching.springaop.CacheAspect" />
	<bean id="calc" class="caching.springaop.Calculator" />


Now we can use Calculator bean created by Spring:

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
Calculator calc = (Calculator) ctx.getBean("calc");

// result will be calculated and stored in cache
logger.info("1 + 2 = " + calc.sum(1, 2));

// result will be retrieved from cache
logger.info("1 + 2 = " + calc.sum(1, 2));

Download full source code as a zip or tar.gz file or browse code online on GitHub.

  1. starsun
    December 8, 2009 at 12:33 AM

    Spring Modules provides a great alternative for declarative caching with @Cacheable annotation, but is still in “draft” status.

    For that, I’m trying to write my own caching system with Spring AOP using annotations and ehcache.

    I found your articles very useful.

    Thank you very much.

    Sorry my english but I speak only spanish 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: