Java Reference
In-Depth Information
How It Works
Before Advices
To create a
before
advice to handle crosscutting concerns before particular program execution points,
you use the
@Before
annotation and include the pointcut expression as the annotation value.
package com.apress.springenterpriserecipes.calculator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class CalculatorLoggingAspect {
private Log log = LogFactory.getLog(this.getClass());
@Before("execution(* ArithmeticCalculator.add(..))")
public void logBefore() {
log.info("The method add() begins");
}
}
This pointcut expression matches the
add()
method execution of the
ArithmeticCalculator
interface. The preceding wildcard in this expression matches any modifier (
public
,
protected
, and
private
) and any return type. The two dots in the argument list match any number of arguments.
To register this aspect, you just declare a bean instance of it in the IoC container. The aspect bean
may even be anonymous if there's no reference from other beans.
<beans ...>
...
<bean class="com.apress.springenterpriserecipes.calculator.
➥
CalculatorLoggingAspect" />
</beans>
You can test your aspect with the following
Main
class:
package com.apress.springenterpriserecipes.calculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Search WWH ::
Custom Search