25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

As you can see, aspect-oriented programming can help you modularize your concerns by using logging or maybe<br />

caching to separate them from your business logic and thereby avoiding scattering and tangling.<br />

But wait, how will caching use these advices? Well, let’s find out by reviewing Listing 8-14. You are going to use<br />

the around advice type to achieve caching.<br />

Listing 8-14. CachingModule.java<br />

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

import java.util.HashMap;<br />

import java.util.Map;<br />

import org.aopalliance.intercept.MethodInterceptor;<br />

import org.aopalliance.intercept.MethodInvocation;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

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

public class CachingModule implements MethodInterceptor {<br />

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

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

public Object invoke(MethodInvocation invocation) throws Throwable {<br />

Object result = null;<br />

Type documentType = null;<br />

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

if("findByType".equals(invocation.getMethod().getName()) &&<br />

invocation.getArguments().length == 1 &&<br />

invocation.getArguments()[0] instanceof Type){<br />

documentType = (Type)invocation.getArguments()[0];<br />

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

if(cache.containsKey(documentType.getName())){<br />

log.debug("@@@(Caching) Found in Cache!");<br />

return cache.get(documentType.getName());<br />

}<br />

log.debug("@@@(Caching) Not Found! but is cachable!");<br />

result = invocation.proceed();<br />

cache.put(documentType.getName(), result);<br />

return result;<br />

}<br />

}<br />

return invocation.proceed();<br />

}<br />

Listing 8-14 shows the implementation of the invoke method; here you are going to specialize your logic. You are<br />

going to declare a Map class that will hold the values from different keys; these keys will be the document’s type. You<br />

are going to cache only the findByType method, so if it is called you can see if the document’s type exists in the Map.<br />

If not, you add it into the Map and return it; if it exists in the Map, then just return it.<br />

104

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

Saved successfully!

Ooh no, something went wrong!