package top.finen.spring.aop.helloworld;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class ArithmeticCalculatorLoggingProxy {
private ArithmeticCalculator target;
public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
this.target = target;
}
public ArithmeticCalculator getLoggingProxy() {
ArithmeticCalculator arithmeticCalculator = null;
//代理对象有那一个类加载器加载
ClassLoader loader = target.getClass().getClassLoader();
//代理对象的类型,即其中有那些方法
Class[] interfaces = new Class[]{ArithmeticCalculator.class};
//当调用代理对象其中的方法时,该执行的代码
InvocationHandler handler = new InvocationHandler() {
/**
*
* @param proxy 正在返回的那个代理对象,一般情况下,在invoke方法中都不使用该对象。
* @param method 正在被调用的方法
* @param args 方法调用时,传入的参数
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
//日志
System.out.println("The method " + methodName + " begin with " + Arrays.asList(args));
Object result = null;
//返回方法
try {
//前置通知
result = method.invoke(target, args);
//返回通知:可以访问到方法的返回值
} catch (Exception e) {
e.printStackTrace();
//异常通知
}
//后置通知:因为方法可能出现异常,所以访问不到方法的返回值
//日志
System.out.println("The method " + methodName + " ends with " + result);
return result;
}
};
arithmeticCalculator = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, handler);
return arithmeticCalculator;
}
}
public class Main {
public static void main(String[] args) {
ArithmeticCalculator target = new ArithmeticCalculatorImpl();
ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getLoggingProxy();
int result = proxy.add(1, 2);
System.out.println("------" + result);
}
}
加入Jar包 com.springsource.org.aopalliance-1.0.0.jar com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar spring-aop-4.3.18.RELEASE.jar spring-aspects-4.3.18.RELEASE.jar
commons-logging-1.1.1.jar spring-beans-4.3.18.RELEASE.jar spring-context-4.3.18.RELEASE.jar spring-core-4.3.18.RELEASE.jar spring-expression-4.3.18.RELEASE.jar
在配置文件中加入aop的命名空间
基于注解的方式
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
把横切关注点的代码抽象到切面的类中。
1.切面首先是一个IOC的bean,即加入@Component注解 2.切面还需要加入@Aspect注解
在类中声明各种通知:
1.声明一个方法
2.在方法前加入@Before注解
@Before("execution(public int top.finen.spring.aop.impl.ArithmeticCalculator.*(int, int))")
1
可以在声明的通知方法中声明一个类型为JoinPoint的参数,然后就能访问链接细节,如方法名称和参数。
@Aspect
@Component
public class LoggingAspect {
//声明该方法是一个前置通知:在目标方法之前执行
@Before("execution(public int top.finen.spring.aop.impl.ArithmeticCalculator.*(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 + " begins with:" + args);
}
}
package top.finen.spring.aop.impl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @author finen
* 把这个类声明为一个切面:需要把该类放入到IOC容器中,在声明为一个切面
* 可以使@Order注解指定切面优先级,优先级值越小优先级越高
*/
@Order(2)
@Aspect
@Component
public class LoggingAspect {
/**
* 定义一个方法:用于声明切入点表达式,一般地,该方法中不需要切入其他的的代码
* 使用@Pointcut来声明切入点表达式
* 后面的其他通知直接使用方法名引用当前切入点表达式
*/
@Pointcut("execution(public int top.finen.spring.aop.impl.ArithmeticCalculator.*(int, int))")
public void declareJoinPointExpression() {}
/**
* 声明该方法是一个前置通知:在目标方法之前执行
* 在声明能获取到执行的参数
* @param joinPoint
*/
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + " begins with:" + args);
}
/**
* 后置通知:在目标方法执行后(无论是否发生异常),执行的通知
* 在后置通知中还不能访问目标方法执行的结果。
* @param joinPoint
*/
@After("declareJoinPointExpression()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " end");
}
/**
* 在方法结束受执行代码的之后返回的通知
* 返回通知是可以访问到方法的返回值的
* @param joinPoint
*/
@AfterReturning(value = "declareJoinPointExpression()",
returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " end with: " + result);
}
/**
* 在方法出现异常时,会执行的代码
* 可以访问到异常对象,且可以指定出现特定异常时在执行通知代码。
* @param joinPoint
* @param exception
*/
@AfterThrowing(value = "declareJoinPointExpression()",
throwing = "exception")
public void afterThrowing(JoinPoint joinPoint, Exception exception) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " throwing with: " + exception);
}
/**
* 环绕通知需要携带ProceedingJoinPoint类型的参数
* 环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
* 环绕通知必须有返回值,且返回值为目标方法的返回值
* @param proceedingJoinPoint
*/
@Around("declareJoinPointExpression()")
public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) {
Object result = null;
String methodName = proceedingJoinPoint.getSignature().getName();
//执行目标方法
try {
//前置通知
System.out.println("The method " + methodName + " begins with:" + Arrays.asList(proceedingJoinPoint.getArgs()));
result = proceedingJoinPoint.proceed();
//返回通知
System.out.println("The method " + methodName + " end with:" + result);
} catch (Throwable throwable) {
//异常通知
System.out.println("The method " + methodName + " throwing with: " + throwable);
throwable.printStackTrace();
}
//后置通知
System.out.println("The method " + methodName + " end");
return result;
}
}
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
import java.util.List;
/**
* @author finen
* 把这个类声明为一个切面:需要把该类放入到IOC容器中,在声明为一个切面
* 可以使@Order注解指定切面优先级,优先级值越小优先级越高
*/
public class LoggingAspect {
public void declareJoinPointExpression() {}
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + " begins with:" + args);
}
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " end");
}
public void afterReturning(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " end with: " + result);
}
public void afterThrowing(JoinPoint joinPoint, Exception exception) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " throwing with: " + exception);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!--配置bean-->
<bean id="arithmeticCalculator" class="top.finen.spring.aop.xml.ArithmeticCalculatorImpl"></bean>
<bean id="loggingAspect" class="top.finen.spring.aop.xml.LoggingAspect"></bean>
<bean id="validationAspect" class="top.finen.spring.aop.xml.ValidationAspect"></bean>
<!--配置AOP-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* top.finen.spring.aop.xml.ArithmeticCalculator.*(int, int))"/>
<!--配置切面以及配置-->
<aop:aspect ref="loggingAspect" order="2">
<aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
<aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="exception"></aop:after-throwing>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"></aop:after-returning>
</aop:aspect>
<aop:aspect ref="validationAspect" order="1">
<aop:before method="validateArgs" pointcut-ref="pointcut"></aop:before>
</aop:aspect>
</aop:config>
</beans>