1.面向切面编程
在程序原有纵向执行流程中,针对某一个或某一些方法添加通知,形成横切面的过程叫做面向切面编程
2.常用概念
原有功能:切点,pointcut
前置通知:在切点之前执行的功能,before advice
后置通知:在切点之后执行的功能,after advice
如果切点执行过程中出现异常,会触发异常通知,throws advice
所有功能的总称叫做切面
织入:把切面嵌入原有功能的过程叫做织入
3.Schema-based方式
每个通知都需要实现接口或类
配置spring配置文件时在<aop:config>配置
4.AspectJ方式
每个通知不需要实现接口或类
配置spring配置文件时在<aop:config>的子标签<aop:aspect>中配置
5.Schema-based
Demo.java
public class Demo { public void demo1(){ System.out.println("demo1"); } public void demo2(){ System.out.println("demo2"); } public void demo3(){ System.out.println("demo3"); } }
(1)导入jar包
aopalliance-1.0.jar
aspectjweaver-1.9.2.jar
(2)新建前置通知类
arg0:切点方法对象Method对象
arg1:切点方法参数
arg2:切点方法所在类的对象
public class MyBeforeAdvice implements MethodBeforeAdvice{ @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("执行前置通知"); } }
(3)新建后置通知类
arg0:切点方法返回值
arg1:切点方法对象Method对象
arg2:切点方法参数
arg3:切点方法所在类的对象
public class MyAfterAdvice implements AfterReturningAdvice { @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("执行后置通知"); } }
(4)配置spring配置文件
<?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.xsd"> <!-- 配置通知类的对象,在切面中引入 --> <bean id="mybefore" class="com.mxj.advice.MyBeforeAdvice"></bean> <bean id="myafter" class="com.mxj.advice.MyAfterAdvice"></bean> <!-- 配置切面 --> <aop:config> <!-- 配置切点 *通配符:匹配任意方法名,任意类名,任意一级包名;(..):任意类型参数--> <aop:pointcut expression="execution(* com.mxj.test.Demo.demo2())" id="mypoint"/> <!-- 通知 --> <aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/> <aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/> </aop:config> <!-- 配置Demo类 --> <bean id="demo" class="com.mxj.test.Demo"></bean> </beans>
6.配置异常通知的步骤(AspectJ方式)
(1)只有切点报异常才能触发异常通知
(2)在spring中只有AspectJ方式提供了异常通知的方法
(3)实现步骤
新建类,在类中写任意名称的方法
public class MyThrowAdvice { public void myexception(){ System.out.println("执行异常通知"); } }
在spring配置文件中配置
<aop:aspect>的ref属性表示:方法在哪个类中
<aop:xxxx/>表示xxx通知
method:当触发这个通知时调用哪个方法
throwing:异常对象名,必须和通知中方法参数名相同(可以不在通知中声明异常对象)
<bean id="mythrow" class="com.mxj.advice.MyThrowAdvice"></bean> <aop:config> <aop:aspect ref="mythrow"> <aop:pointcut expression="execution(* com.mxj.test.Demo.demo1())" id="mypoint"/> <aop:after-throwing method="myexception()" pointcut-ref="mypoint" throwing="e"/> </aop:aspect> </aop:config> <bean id="demo" class="com.mxj.test.Demo"></bean>
7.异常通知(Schema-based方式)