AspectJ是目前最流行的AOP框架。
本例采用注解的方式实现前置通知,xml配置方式稍后讲解
//接口
public interface Calculator {
int add(int i,int j);
int sub(int i,int j);
}
//接口实现类
@Component
public class CalculatorImpl implements Calculator{
@Override
public int add(int i, int j) {
int result = i+j;
return result;
}
@Override
public int sub(int i, int j) {
int result = i-j;
return result;
}
}
//切面类
package com.test.aop.impl;
import java.util.Arrays;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* 切面类
* 1.需要将该类放入到IOC容器中
* 2.再将它申明为一个切面
*/
@Aspect
@Component
public class LoggingAspect {
//声明该方法是一个前置通知
//在如下方法开始执行之前执行
@Before("execution(public int com.test.aop.impl.CalculatorImpl.add(int, int))")
public void beforeMethod(JoinPoint joinPoint) {
//获取方法名
String methodName = joinPoint.getSignature().getName();
//获取方法参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method" + methodName + "begin"+args);
}
//后置通知
//目标方法执行之后(无论是否发生异常),执行的通知
@After("execution(* com.test.aop.impl.CalculatorImpl.*(int,int))")
public void afterMethod(JoinPoint joinPoint) {
//获取方法名
String methodName = joinPoint.getSignature().getName();
System.out.println("The method" + methodName + "end");
}
}
//main方法
public class Main {
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Calculator calculator = ctx.getBean(Calculator.class);
int result = calculator.add(1, 2);
System.out.println(result);
}
}
//xml配置文件
<!-- 自动扫描包 -->
<context:component-scan base-package="com.test.aop.impl"></context:component-scan>
<!-- 使AspectJ注解起作用,为匹配的类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
//输出结果
The methodaddbegin[1, 2]
The methodaddend
3