@Aspect
注解(@AspectJ 注解方式)来实现。IsModified
接口, 以便简化缓存机制(在AspectJ社区,引入也被称为内部类型声明(inter))。pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd
">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>mashibin_spring_01artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>cglibgroupId>
<artifactId>cglibartifactId>
<version>3.3.0version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.5version>
dependency>
<dependency>
<groupId>aopalliancegroupId>
<artifactId>aopallianceartifactId>
<version>1.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>5.2.3.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>5.3.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.2.3.RELEASEversion>
dependency>
dependencies>
project>
创建applicationsContext.xml
配置applicationsContext.xml
<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
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<context:component-scan base-package="com.aop">context:component-scan>
<aop:aspectj-autoproxy>aop:aspectj-autoproxy>
beans>
calculator 接口(模拟计算器)
package com.aop.service;
public interface calculator {
public int add(int i,int j);
public int sub(int i,int j);
public int mult(int i,int j);
public int div(int i,int j);
}
Mycalculator类(实现计算器接口)
package com.aop.service;
import org.springframework.stereotype.Service;
@Service
public class Mycalculator 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;
}
@Override
public int mult(int i, int j) {
int result = i * j;
return result;
}
@Override
public int div(int i, int j) {
int result = i / j;
return result;
}
}
LogUtil类(日志类,也叫通知类),加入ioc注解和aop注解,还有切入点表达式
package com.aop.utils;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Controller;
@Controller
@Aspect
public class LogUtil {
@Before("execution(public int com.aop.service.Mycalculator.*(int,int))")
public static void start(){
System.out.println("方法开始执行");
}
@AfterReturning("execution( public int com.aop.service.Mycalculator.*(int,int))")
public static void stop(){
System.out.println("方法执行完成");
}
@AfterThrowing("execution( public int com.aop.service.Mycalculator.*(int,int))")
public static void logException(){
System.out.println("方法出现异常");
}
@After("execution( public int com.aop.service.Mycalculator.*(int,int))")
public static void end(){
System.out.println("方法执行结束了......");
}
}
给各个类添加注解和切入点表达式(上方代码已经添加)
给LogUtil添加@Component注解
给MyCalculator添加@Service注解
在LogUtil.java中添加@Aspect注解
在LogUtil类中设置方法在什么时候执行
设置下面方法在什么时候运行
切入点白表达式:
*号:
1、匹配一个或者多个字符
execution( public int com.mashibing.inter.My*alculator.*(int,int))
2、匹配任意一个参数,
execution( public int com.mashibing.inter.MyCalculator.*(int,*))
3、只能匹配一层路径,如果项目路径下有多层目录,那么*只能匹配一层路径
4、权限位置(访问修饰符)不能使用*,如果想表示全部权限,那么不写即可
execution( * com.mashibing.inter.MyCalculator.*(int,*))
…号:
1、匹配多个参数,任意类型参数
execution( * com.mashibing.inter.MyCalculator.*(…))
2、匹配任意多层路径
execution( * com.mashibing…MyCalculator.*(…))
在写表达式的时候,可以有N多种写法,但是有一种最偷懒和最精确的方式:
最偷懒的方式:execution(* *(…)) 或者 execution(* *.*(…))
最精确的方式:execution( public int com.mashibing.inter.MyCalculator.add(int,int))
除此之外,在表达式中还支持 &&、||、!的方式
&&:两个表达式同时
execution( public int com.mashibing.inter.MyCalculator.*(…)) && execution(* *.*(int,int) )
||:任意满足一个表达式即可
execution( public int com.mashibing.inter.MyCalculator.*(…)) && execution(* *.*(int,int) )
!:只要不是这个位置都可以进行切入
&&:两个表达式同时
execution( public int com.mashibing.inter.MyCalculator.*(…))
import com.aop.service.calculator;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class aopTaet {
@Test
public void test1(){
//读取配置文件
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean对象
calculator mycalculator = context.getBean( calculator.class);
//执行方法
mycalculator.add(1,2);
}
}
@Before("execution(public int com.aop.service.Mycalculator.*(int,int))")
public static void start(JoinPoint joinPoint) {
// 获取方法签名
Signature signature = joinPoint.getSignature();
// 获取方法名
String name = signature.getName();
//获取方法参数
Object[] args = joinPoint.getArgs();
System.out.println(name+"方法开始执行--Before,方法参数是:" + Arrays.asList(args));
}
切入点表达式中添加returning,在方法中添加Object参数:
@AfterReturning(value = "execution( public int com.aop.service.Mycalculator.*(int,int))",returning = "result")
public static void stop(JoinPoint joinPoint,Object result) {
// 获取方法签名
Signature signature = joinPoint.getSignature();
// 获取方法名
String name = signature.getName();
System.out.println(name + "方法执行完成--AfterReturning,返回值:"+result);
}
切入点表达式中添加trowing,在方法中添加Exception参数,但是两者的属性名必须一致
@AfterThrowing(value = "execution( public int com.aop.service.Mycalculator.*(int,int))",throwing = "e")
public static void logException(JoinPoint joinPoint,Exception e) {
// 获取方法签名
Signature signature = joinPoint.getSignature();
// 获取方法名
String name = signature.getName();
System.out.println(name+"方法出现异常--AfterThrowing,异常信息"+e);
}
作用:简化代码编写
步骤:
随便生命一个没有实现的返回void的空方法
给方法上标注@Potintcut注解
package com.mashibing.util;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
public class LogUtil {
@Pointcut("execution( public int com.mashibing.inter.MyCalculator.*(int,int))")
public void myPoint(){}
@Before("myPoint()")
public static void start(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法开始执行,参数是:"+ Arrays.asList(args));
}
@AfterReturning(value = "myPoint()",returning = "result")
public static void stop(JoinPoint joinPoint,Object result){
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法执行完成,结果是:"+result);
}
@AfterThrowing(value = "myPoint()",throwing = "exception")
public static void logException(JoinPoint joinPoint,Exception exception){
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法出现异常:"+exception.getMessage());
}
@After("myPoint()")
private int end(JoinPoint joinPoint){
String name = joinPoint.getSignature().getName();
System.out.println(name+"方法执行结束了......");
return 0;
}
}
@Around("mypoint()")
public Object myround(ProceedingJoinPoint proceedingJoinPoint){
Object[] args = proceedingJoinPoint.getArgs();
String name = proceedingJoinPoint.getSignature().getName();
Object proceed = null;
try {
System.out.println("环绕前置通知:"+name+"方法开始,参数是"+Arrays.asList(args));
//利用反射调用目标方法,就是method.invoke()
proceed = proceedingJoinPoint.proceed(args);
System.out.println("环绕返回通知:"+name+"方法返回,返回值是"+proceed);
} catch (Throwable e) {
System.out.println("环绕异常通知"+name+"方法出现异常,异常信息是:"+e);
}finally {
System.out.println("环绕后置通知"+name+"方法结束");
}
return proceed;
}
总结
总结:环绕通知的执行顺序是优于普通通知的,具体的执行顺序如下:
环绕前置–>普通前置–>目标方法执行–>环绕正常结束/出现异常–>环绕后置–>普通后置–>普通返回或者异常。
但是需要注意的是,如果出现了异常,那么环绕通知会处理或者捕获异常,普通异常通知是接收不到的,因此最好的方式是在环绕异常通知中向外抛出异常。
AOP基于注解的配置过于麻烦,一般不采用,但是还得有基础的了解。
配置文件:
<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
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<context:component-scan base-package="com.mashibing">context:component-scan>
<aop:aspectj-autoproxy>aop:aspectj-autoproxy>
<bean id="logUtil" class="com.mashibing.util.LogUtil2">bean>
<bean id="securityAspect" class="com.mashibing.util.SecurityAspect">bean>
<bean id="myCalculator" class="com.mashibing.inter.MyCalculator">bean>
<aop:config>
<aop:pointcut id="globalPoint" expression="execution(public int com.mashibing.inter.MyCalculator.*(int,int))"/>
<aop:aspect ref="logUtil">
<aop:pointcut id="mypoint" expression="execution(public int com.mashibing.inter.MyCalculator.*(int,int))"/>
<aop:before method="start" pointcut-ref="mypoint">aop:before>
<aop:after method="end" pointcut-ref="mypoint">aop:after>
<aop:after-returning method="stop" pointcut-ref="mypoint" returning="result">aop:after-returning>
<aop:after-throwing method="logException" pointcut-ref="mypoint" throwing="exception">aop:after-throwing>
<aop:around method="myAround" pointcut-ref="mypoint">aop:around>
aop:aspect>
<aop:aspect ref="securityAspect">
<aop:before method="start" pointcut-ref="globalPoint">aop:before>
<aop:after method="end" pointcut-ref="globalPoint">aop:after>
<aop:after-returning method="stop" pointcut-ref="globalPoint" returning="result">aop:after-returning>
<aop:after-throwing method="logException" pointcut-ref="globalPoint" throwing="exception">aop:after-throwing>
<aop:around method="myAround" pointcut-ref="mypoint">aop:around>
aop:aspect>
aop:config>
beans>