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 20:29:30,241 DEBUG [main] @@@@(BEFORE) Method called: listAll<br />

2014-02-23 20:29:30,241 DEBUG [main] @@@@(BEFORE) No arguments passed.<br />

2014-02-23 20:29:30,241 DEBUG [main] @@@@(BEFORE) Method called: findByLocation<br />

2014-02-23 20:29:30,241 DEBUG [main] @@@@(BEFORE) Argument passed:/some/path/<br />

2014-02-23 20:29:30,241 ERROR [main] findByLocation not yet implemented.<br />

It’s magic! Yes! You are now advising your code, removing the entire scattering and tangling of the logs. Your<br />

SearchEngine implementation is now clean and you can just focus on your business logic.<br />

After Advice<br />

The after advice will be after the method call, and you can get a hold of the return value. This advice is done by<br />

implementing the AfterReturningAdvice interface class. See Listing 8-8 for an example.<br />

Listing 8-8. AfterLoggingModule.java<br />

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

import java.lang.reflect.Method;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

import org.springframework.aop.AfterReturningAdvice;<br />

public class AfterLoggingModule implements AfterReturningAdvice {<br />

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

}<br />

public void afterReturning(Object returnValue, Method method,<br />

Object[] args, Object target) throws Throwable {<br />

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

log.debug("@@@@(AFTER) Method called: " + method.getName());<br />

if(args.length ==0 )<br />

log.debug("@@@@(AFTER) No arguments passed.");<br />

for(Object arg:args)<br />

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

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

}<br />

}<br />

Listing 8-8 implements the method afterReturning that will have the returned value, the method that was<br />

intercepted, the arguments of the method, and the object where the method was intercepted.<br />

Now let’s modify your XML. Remember it will almost be the same as Listing 8-7, but now you are going to change<br />

some ids, as shown in Listing 8-9.<br />

98

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

Saved successfully!

Ooh no, something went wrong!