25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Give Advice to Your <strong>Spring</strong> Application<br />

2014-02-23 21:07:04,680 DEBUG [main] @@@(Caching) Is cachable!!<br />

2014-02-23 21:07:04,680 DEBUG [main] @@@(Caching) Found in Cache!<br />

2014-02-23 21:07:04,680 DEBUG [main] It should be now cached!<br />

2014-02-23 21:07:04,680 DEBUG [main] @@@(Caching) review if this call is cachable...<br />

2014-02-23 21:07:04,680 DEBUG [main] @@@(Caching) Is cachable!!<br />

2014-02-23 21:07:04,680 DEBUG [main] @@@(Caching) Found in Cache!<br />

AOP with Annotations<br />

The <strong>Spring</strong> <strong>Framework</strong> also supports and plays nice with AspectJ. AspectJ is the library that initially started providing<br />

AOP support for Java by providing a compiler and a new aspect programming language; later it provided some Java 5<br />

annotation features. So the <strong>Spring</strong> <strong>Framework</strong> AOP extension provides support for @Aspect, @Before, @After,<br />

@AfterReturning, @Around, and @AfterThrowing annotations. Listing 8-17 is an example of your caching solution<br />

using AspectJ and <strong>Spring</strong>.<br />

Listing 8-17. Caching.java<br />

package com.apress.isf.spring.annotated.aop;<br />

import java.util.HashMap;<br />

import java.util.Map;<br />

import org.aspectj.lang.ProceedingJoinPoint;<br />

import org.aspectj.lang.annotation.Around;<br />

import org.aspectj.lang.annotation.Aspect;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

import org.springframework.stereotype.Component;<br />

import com.apress.isf.java.model.Type;<br />

import com.apress.isf.spring.aop.CachingModule;<br />

@Component<br />

@Aspect<br />

public class Caching {<br />

private static final Logger log = LoggerFactory.getLogger(CachingModule.class);<br />

private static final Map cache = new HashMap();<br />

@Around("execution(* com.apress.isf.java.service.SearchEngine.*(..))")<br />

public Object caching(ProceedingJoinPoint pjp) throws Throwable {<br />

Object result = null;<br />

Type documentType = null;<br />

log.debug("@@@(Caching) review if this call is cachable...");<br />

if("findByType".equals(pjp.getSignature().getName()) &&<br />

pjp.getArgs().length == 1 && pjp.getArgs()[0] instanceof Type){<br />

documentType = (Type)pjp.getArgs()[0];<br />

log.debug("@@@(Caching) Is cachable!!");<br />

107

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!