AOP即面向切面编程,是Spring的一个特点之一,简而言之就是可以将一个方法声明为切面,然后可以在切面之前和之后执行特定的方法。例如把foo()声明为切面的话,我们想在foo()之前打印日志,在foo()之后打印日志(无论报不报错),在foo()出错时打印日志,在foo()成功执行时打印日志。
其实我们知道可以用代理模式来实现这个功能,但是会比较难写,以后写出来再插链接:
不存在的链接~~~~(>_<)~~~~
使用Spring AOP可以很容易的实现这个功能,这其中又可以分为用注解方式和用xml配置的方式
AspectJ是Java社区中最完整最流行的AOP框架,在Spring2.0以上版本中,可以使用基于AspectJ注解或基于XML配置AOP
使用AspectJ需要添加新的依赖包,这是aspectj的编织器,我是使用maven添加的
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
不懂得使用maven的话,直接搜索aspectjweaver.jar也可以搜到包,然后再手动添加也行
一、用注解的方式实现AOP
写一个简单的类,可以进行四则运算
package aop;
import org.springframework.stereotype.Component;
@Component
public class ArithmeticCaculato {
public int add(int i, int j) {
int result = i + j;
return result;
}
public int sub(int i, int j) {
int result = i - j;
return result;
}
public int mul(int i, int j) {
int result = i * j;
return result;
}
public int div(int i, int j) {
int result = i / j;
return result;
}
}
然后再写切面的类,进行切面前后的通知
package aop;
import java.util.Arrays;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.jdbc.ReturningWork;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
/*
* 定义一个方法,用于声明切入点表达式,一般的,该方法中再不需要填入其他代码
* 使用@PointCut来声明切入点表达式
* 后面的其他通知直接使用方法名来引用当前的切入点表达式
*/
@Pointcut("execution(public int aop.ArithmeticCaculator.*(..))")
public void declareJointPointExpression() {
}
/*
* 在ArithmeticCaculator接口的每一个实现类的每一个方法开始前执行这一段代码
*/
@Before("declareJointPointExpression()")
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object [] args = joinPoint.getArgs();
System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
}
//后置通知:在目标方法执行后(无论是否发生异常),执行的通知
//在后置通知中还不能访问目标方法执行的结果
@After("declareJointPointExpression()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + " ends");
}
@AfterReturning(value = "declareJointPointExpression()",
returning ="result")
public void afterReturning(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + " return with " + result);
}
/*
* 在目标方法出现异常时会执行的代码
* 可以访问到异常对象;且可以指定在出现特定异常时再执行特定代码
*/
@AfterThrowing(value = "declareJointPointExpression()",
throwing ="ex")
public void afterThrowing(JoinPoint joinPoint, Exception ex) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + " occurs exception " + ex);
}
/*
* 环绕通知需要携带ProceedingJoinPoint类型的参数
* 环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
* 且环绕通知必需有返回值,返回值即为目标方法的返回值
* @param pjd
*/
/*
*
@Around("execution(public int aop.ArithmeticCaculator.*(..))")
public Object aroundMethod(ProceedingJoinPoint pjd) throws Throwable {
Object result = null;
String methodName = pjd.getSignature().getName();
try {
//前置通知
System.out.println("aroundMethod " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
result = pjd.proceed();
//返回通知
System.out.println("aroundMethod " + methodName + " return with " + result);
} catch (Exception e) {
// 异常通知
System.out.println("aroundMethod " + methodName + " throwing " + e.toString());
//e.printStackTrace();
}
//后置通知
System.out.println("aroundMethod " + methodName + " ends with " + Arrays.asList(pjd.getArgs()));
return result;
}
*/
}
需要注意的是,上面的代码我们注意到有个aroundMethod,这个方法相当于前面一整套的declareJointPointExpression()、beforeMethod(JoinPoint joinPoint)、afterMethod(JoinPoint joinPoint)、afterReturning(JoinPoint joinPoint, Object result)、afterThrowing(JoinPoint joinPoint, Exception ex),一般不使用这个方法,在这里写出来只是说明有这个方法。
在配置文件中这样写
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="aop"></context:component-scan>
<!-- 配置自动为匹配aspectJ注解的Java类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
写个main函数测试一下:
package aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
ArithmeticCaculator arithmeticCaculator = (ArithmeticCaculator)ctx.getBean("arithmeticCaculator");
System.out.println(arithmeticCaculator.getClass().getName());
int result = arithmeticCaculator.add(2, 1);
System.out.println("result: " + result);
result = arithmeticCaculator.div(1000, 0);
System.out.println("result: " + result);
}
}
可以看到输出结果:
aop.ArithmeticCaculatorImpl
validate: [2, 1]
The method add begins with [2, 1]
The method add ends
The method add return with 3
result: 3
validate: [1000, 0]
The method div begins with [1000, 0]
The method div ends
The method div occurs exception java.lang.ArithmeticException: / by zero
可以看出来运行时正常的。
二、用xml配置文件实现AOP
使用xml文件配置的时候,修改一下LoggingAspect类,不用加注解
在Spring bean的配置文件中配置切面
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 配置bean -->
<bean id="arithmeticCaculator"
class="aop.xml.ArithmeticCaculatorImpl"></bean>
<!-- 配置切面的bean -->
<bean id="loggingAspect"
class="aop.xml.LoggingAspect"></bean>
<!-- 配置AOP -->
<aop:config>
<!-- 配置切点表达式 -->
<aop:pointcut expression="execution(* aop.xml.ArithmeticCaculator.*(int, int))"
id="pointcut"/>
<!-- 配置切面及通知 -->
<aop:aspect ref="loggingAspect">
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<aop:after method="afterMethod" pointcut-ref="pointcut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<aop:around method="aroundMethod" pointcut-ref="pointcut" />
</aop:aspect>
</aop:config>
</beans>
以上就是Spring的AOP