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

}<br />

}<br />

try{<br />

engineProxy.findByLocation("/some/path/");<br />

}catch(Exception ex){<br />

log.error(ex.getMessage());<br />

}<br />

If you run this test with<br />

gradle :ch08:test<br />

you will have the following output:<br />

2014-02-23 20:04:06,217 DEBUG [main] Using <strong>Spring</strong> AOP:<br />

2014-02-23 20:04:06,404 ERROR [main] findByLocation not yet implemented.<br />

Where are the logs? Well, you removed them from your implementation (see SearchEngineService.java, which<br />

is shown in Listing 8-3). You also added a new method in your interface (see Listing 8-2). And in your implementation<br />

you just throw an UnsupportedOperationException exception, that’s why you are seeing the error log.<br />

Next, let’s learn more about each advice type: before, after, around, and after throw.<br />

Before Advice<br />

You are going to create your first advice type. <strong>Spring</strong> AOP provides a MethodBeforeAdvice interface, and it provides a<br />

before method for its implementation. This method will be called before the object’s method execution (see Listing 8-6).<br />

In other words, you are intercepting a method call before its execution.<br />

Listing 8-6. BeforeLoggingModule.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.MethodBeforeAdvice;<br />

public class BeforeLoggingModule implements MethodBeforeAdvice {<br />

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

}<br />

96<br />

public void before(Method method, Object[] args, Object target)<br />

throws Throwable {<br />

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

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

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

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

for(Object arg:args)<br />

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

}<br />

}

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

Saved successfully!

Ooh no, something went wrong!