AspectJ:Java社区中最完整、最流行的AOP框架。
在Spring2.0以上版本中,可以使用基于AspectJ注解或基于XML配置的AOP。
在Spring中2启用AspectJ注解支持:
1、要在 Spring应用中使用AspectJ注解,需要添加spring-aspect、aspectj-weaver、aopalliance依赖
2、将aop Schema添加到<beans>根元素
3、要在SpringIOC容器中启用AspectJ注解支持,只要在Bean配置文件中定义一个空的XML元素:<aop:aspectj-autoproxy>
4、在Spring IOC容器侦测到Bean配置文件中的<aop:aspectj-autoproxy>元素时,会自动与AspectJ切面匹配的Bean创建代理
一、基于注解的方式
1、依赖
2、在配置中加入aop的命名空间
3、基于注解的方式:
①在配置文件中加入:<aop:aspectj-autoproxy>
配置文件:
<?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:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置自动扫描的包-->
<context:component-scan base-package="com.aop.service,com.aop.notice,com.aop.test"/>
<!--使AspectJ注解起作用:自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
②把横切关注点的代码抽象到切面的类中
切面首先是一个IOC容器中的Bean,即加入@Component注解
切面还需要加入@AspectJ注解
③在类中声明各种通知:
1、声明一个方法
2、在方法前加入通知
@AspectJ支持的5中通知:
—@Before:前置通知在方法执行前执行
—@After:最终通知,在方法执行后执行
—@AfterReturning:返回后通知(后置通知),在方法返回结果之后执行
—@AfterThrowing:异常通知,在方法抛出异常后执行
—@Around:环绕通知,围绕着方法执行
④我们可以在通知方法中声明一个类型为JoinPoint参数,然后就能访问链接细节,如方法名称和参数值
切面类:
package com.aop.notice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* 把这个类声明为一个切面:
* 1、需要把该类放入到容器中(就是加上@Component注解)
* 2、再声明为一个切面(加上@AspectJ注解)
*
* @author chenpeng
* @date 2018/6/3 23:20
*/
@Aspect
@Component
public class LoggingAspect {
//声明该方法为一个前置通知:在目标方法开始之前执行
//execution中是AspectJ表达式
@Before(value = "execution(* com.aop.service.UserServiceImple.addUser(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("beforeMethod "+methodName+" and "+args);
}
}
在使用的时候报错:因为动态代理不能用接口的实现类来转换Proxy的实现类,它们是同级,应该用共同的接口来转换。
改为这样:
package com.aop.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.aop.service.UserService;
/**
* AOPTest:测试代码
*/
public class AOPTest {
@Test
public void test01(){
//1、创建SpringIOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("aop.xml");
//2、从IOC容器中获取Bean的实例
UserService userService = (UserService) context.getBean("userService");
//3、使用Bean
userService.addUser("cjj"); // 一个连接点
}
}
其他通知:
package com.aop.notice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* 把这个类声明为一个切面:
* 1、需要把该类放入到容器中(就是加上@Component注解)
* 2、再声明为一个切面(加上@AspectJ注解)
*
* @author chenpeng
* @date 2018/6/3 23:20
*/
@Aspect
@Component
public class LoggingAspect {
//声明该方法为一个前置通知:在目标方法开始之前执行
//execution中是AspectJ表达式
@Before(value = "execution(* com.aop.service.UserServiceImple.addUser(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("beforeMethod "+methodName+" start with "+args);
}
//后置通知,就是在目标方法执行之后(无论是否发生异常)执行的通知
//后置通知中不能访问目标方法的返回结果
@After(value = "execution(* com.aop.service.UserServiceImple.addUser(..))")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("afterMethod "+methodName+" end with "+args);
}
//返回通知,在方法正常结束之后执行的代码
//返回通知是可以访问到方法的返回值的
@AfterReturning(value = "execution(* com.aop.service.UserServiceImple.addUser(..))",returning = "result")
public void afterReturning(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("afterReturning "+methodName+" end with "+result);
}
//返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
//可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
@AfterThrowing(value = ""execution(* com.aop.service.UserServiceImple.addUser(..))",throwing = "ex")
public void afterThrowing(JoinPoint joinPoint,Exception ex){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("afterThrowing "+methodName+" end with "+ ex );
}
//环绕通知需要携带ProceedingJoinPoint类型的参数
//环绕通知类似于动态代理的全过程,这个类型ProceedingJoinPoint的参数可以决定是否执行目标方法
//且环绕通知必须有返回值,返回值即为目标方法返回值
@Around(value = "execution(* com.aop.service.UserServiceImple.addUser(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint){
Object result = null;
String methodName = proceedingJoinPoint.getSignature().getName();
Object[] args = proceedingJoinPoint.getArgs();
//执行目标方法
try {
//前置通知
System.out.println("beforeMethod "+methodName+" start with "+args);
result = proceedingJoinPoint.proceed();
//返回通知
System.out.println("afterMethod "+methodName+" end with "+result);
} catch (Throwable throwable) {
//异常通知
System.out.println("afterThrowing "+methodName+" exception with "+ throwable );
throwable.printStackTrace();
}
//后置通知
System.out.println("afterMethod "+methodName+" end with "+args);
//System.out.println("around "+proceedingJoinPoint);
return;
}
}
对于切面的优先级
可以在类上使用注解@Order(1),括号中的数字越小,优先级越高
@Order(1)
重用切面的切点表达式:使用@Pointcut
/**
* 定义一个方法,用于声明切入点表达式
*一般的,该方法中不需要添加其他的代码
* 使用@Pointcut来声明切入点表达式
* 后面的其他通知直接使用方法名来引用切入点表达式
*/
@Pointcut(value = "execution(* com.aop.service.UserServiceImple.addUser(..))")
public void declareJoinPointExpress(){ }
//声明该方法为一个前置通知:在目标方法开始之前执行
//execution中是AspectJ表达式
@Before(value = "declareJoinPointExpress()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("beforeMethod "+methodName+" start with "+args);
}
其他切面类中使用:
package com.aop.notice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
*
*/
//可以使用@Order指定切面的优先级,值越小优先级越高
@Order(1)
@Component
@Aspect
public class ValidationAspect {
@Before(value = "FirstAspect.declareJoinPointExpress()")
public void validateArgs(JoinPoint joinPoint){
System.out.println("validateArgs"+ Arrays.asList(joinPoint.getArgs()));
}
}
二、基于XML配置文件的方式
除了使用@AspectJ注解声明切面,Spring还支持在Bean的配置文件中声明切面,这种声明是通过aop Schema中的XML元素完成的。
正常情况下,基于注解的声明要优于基于XML的声明,通过@AspectJ注解,可以与Aspect切面相兼容,而基于XML配置则是Spring专有的。优于@AspectJ得到越来越多AOP框架支持,所以用的更多。
配置方式:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<context:annotation-config></context:annotation-config>
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.aop.service,com.aop.notice,com.aop.test"></context:component-scan>
<!--基于XML配置的AOP-->
<aop:config proxy-target-class="true">
<!-- 配置切入点 -->
<aop:pointcut id="pc01" expression="execution(* com.aop.service.UserServiceImple.addUser(..))"/>
<!-- 配置切面 -->
<aop:aspect ref="firstAspect">
<aop:before method="beforeMethod" pointcut-ref="pc01"/>
<aop:around method="around" pointcut-ref="pc01"/>
<aop:after method="afterMethod" pointcut-ref="pc01"/>
<aop:after-returning method="afterReturning" pointcut-ref="pc01" returning="result"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pc01" throwing="ex"/>
</aop:aspect>
</aop:config>
</beans>
package com.aop.service;
public interface UserService {
public void addUser(String name);
public void updateUser() ;
public void deleteUser() ;
public void query() ;
}
package com.aop.service;
import org.springframework.stereotype.Service;
/**
* UserServiceImple:目标对象
*/
@Service("userService")
public class UserServiceImple implements UserService{
@Override
public void addUser(String name) {
//int i = 1/0;
System.out.println("增加用户。。");
}
@Override
public void updateUser() {
System.out.println("修改用户。。");
}
@Override
public void deleteUser() {
System.out.println("删除用户。。");
}
@Override
public void query() {
System.out.println("查询用户。。");
}
}
package com.aop.notice;
import java.util.Arrays;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* FirstAspect:切面代码
* 把这个类声明为一个切面:
* 1、需要把该类放入到容器中(就是加上@Component注解)
*/
@Component
public class FirstAspect {
//声明该方法为一个前置通知:在目标方法开始之前执行
// @Before(value = "execution(* com.aop.service.UserServiceImple.addUser(..))")
public void beforeMethod(JoinPoint joinPoint){ // 可以选择额外的传入一个JoinPoint连接点对象,必须用方法的第一个参数接收。
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("beforeMethod "+methodName+" and "+args);
}
//后置通知,就是在目标方法执行之后(无论是否发生异常)执行的通知
//后置通知中不能访问目标方法的返回结果
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("afterMethod "+methodName+" and "+args);
}
//返回通知,在方法正常结束之后执行的代码
//返回通知是可以访问到方法的返回值的
public void afterReturning(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("afterReturning "+methodName+" end with "+result);
}
//返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
//可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
public void afterThrowing(JoinPoint joinPoint,Exception ex){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("afterThrowing "+methodName+" end with "+ ex );
}
//环绕通知需要携带ProceedingJoinPoint类型的参数
//环绕通知类似于动态代理的全过程,这个类型ProceedingJoinPoint的参数可以决定是否执行目标方法
//且环绕通知必须有返回值,返回值即为目标方法返回值
public void around(ProceedingJoinPoint proceedingJoinPoint){
Object result = null;
String methodName = proceedingJoinPoint.getSignature().getName();
Object[] args = proceedingJoinPoint.getArgs();
//执行目标方法
try {
//前置通知
System.out.println("beforeMethod "+methodName+" start with "+args);
result = proceedingJoinPoint.proceed();
//返回通知
System.out.println("afterMethod "+methodName+" end with "+result);
} catch (Throwable throwable) {
//异常通知
System.out.println("afterThrowing "+methodName+" exception with "+ throwable );
throwable.printStackTrace();
}
//后置通知
System.out.println("afterMethod "+methodName+" end with "+args);
//System.out.println("around "+proceedingJoinPoint);
return;
}
}
package com.aop.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.aop.service.UserService;
/**
* AOPTest:测试代码
*/
public class AOPTest {
@Test
public void test01(){
//1、创建SpringIOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("aop.xml");
//2、从IOC容器中获取Bean的实例
UserService userService = (UserService) context.getBean("userService");
//3、使用Bean
userService.addUser("cjj"); // 一个连接点
}
}
五种通知的执行顺序
1.在目标方法没有抛出异常的情况下
前置通知 ->
环绕通知的调用目标方法之前的代码 -> 目标方法 -> 环绕通知的调用目标方法之后的代码 ->
后置通知
最终通知
2.在目标方法抛出异常的情况下
前置通知
环绕通知的调用目标方法之前的代码
目标方法 抛出异常 异常通知
最终通知
3.如果存在多个切面
多切面执行时,采用了责任链设计模式。
切面的配置顺序决定了切面的执行顺序,多个切面执行的过程,类似于方法调用的过程,在环绕通知的proceed()执行时,去执行下一个切面或如果没有下一个切面执行目标方法,从而达成了如下的执行过程:
五种通知的常见使用场景
环绕通知 | 控制事务 权限控制 |
后置通知 | 记录日志(方法已经成功调用) |
异常通知 | 异常处理 控制事务 |
最终通知 | 记录日志(方法已经调用,但不一定成功) |
Spring AOP SpringBoot集成
引入AOP依赖包后,不需要去做其他配置。AOP的默认配置属性中,spring.aop.auto属性默认是开启的,也就是说只要引入了AOP依赖后,默认已经增加了@EnableAspectJAutoProxy,不需要在程序主类中增加@EnableAspectJAutoProxy来启用。
切点表达式用于描述切点的位置信息,在此简单描述文中切点表达式的含义。
推荐一个切点表达式总结的博客https://www.cnblogs.com/zhangxufeng/p/9160869.html