Archive

Posts Tagged ‘Spring’

Simple caching with Spring AOP

September 18, 2009 1 comment

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"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	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" />

</beans>

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.