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 />

description: Text Notes, extension: .txt), location: /Users/felipeg/Documents/Random/Clustering with<br />

RabbitMQ.txt), Documents(name: Pro <strong>Spring</strong> Security Book, type: Type(name: WEB, description: Web<br />

Link, extension: .url), location: http://www.apress.com/9781430248187)]<br />

2014-02-23 20:39:40,749 ERROR [main] findByLocation not yet implemented.<br />

The output shows how this advice intercepts the method after it is called, so you can get a hold of the return<br />

value. A different scenario would be to have an audit advice that will trigger an alarm after a special value is returned<br />

by the method intercepted, such as an audit of a bank account that returns a big amount.<br />

Around Advice<br />

This advice, as you may have guessed already, is the combination of the before and after advices, but you can have<br />

more control over it because it will intercept the method call, then you can execute that call and get back a result.<br />

You are executing the after and before advices in one advice. In order to implement this advice, you need to use the<br />

MethodInterceptor interface class (see Listing 8-10).<br />

Listing 8-10. AroundLoggingModule.java<br />

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

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

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

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

public class AroundLoggingModule implements MethodInterceptor {<br />

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

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

Object result = null;<br />

if(log.isDebugEnabled()){<br />

log.debug("@@@@(AROUND-BEFORE) Method called: " +<br />

invocation.getMethod().getName());<br />

if(invocation.getArguments().length ==0 )<br />

log.debug("@@@@(AROUND-BEFORE) No arguments passed.");<br />

for(Object arg:invocation.getArguments())<br />

log.debug("@@@@(AROUND-BEFORE) Argument passed:" + arg);<br />

}<br />

try{<br />

if(log.isDebugEnabled())<br />

log.debug("@@@(AROUND) Processing...");<br />

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

if(log.isDebugEnabled())<br />

log.debug("@@@(AROUND-AFTER) Result: " + result);<br />

return result;<br />

}catch(IllegalArgumentException ex){<br />

100

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

Saved successfully!

Ooh no, something went wrong!