概念
AOP的概念:
面向切面编程,把程序重复的代码提取出来。
在需要执行的时候,使用动态代理技术,在不修改源码的情况下,对以后的方法进行方法增强。
相关概念:
- 连接点(拦截到的方法)
- 切入点(对拦截后的方法进行增强的方法)
- 通知(前置通知@before、后置通知@Afer、异常通知@AfterThrowing、最终通知@AfterReturn)
- 切面(有切入点和通知组成的类)
- 目标对象(代理的目标对象)
使用AOP
1、使用注解配置
- 创建通知类,在通知类上也使用注解配置@Component,交给spring管理
- 在通知类使用@Aspect,声明该类是切面
- 在通知类上设置各种通知
- 在spring配置文件中开启spring对AOP的支持aop:aspectj-autoproxy/
package com.dcy;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/*
五大通知:before、afer、afterThrowing、alterReturning、around
*/
@Component
@Aspect
public class EnhanceMethodManager {
@Pointcut("execution(* com.dcy.srcMethod.*.*(..))") //切入点
public void pt1(){}
@Before("pt1()")//前置通知
public void before(){
System.out.println("执行拦截方法前的代码块");
}
@After("pt1()")/*finally*//后置通知
public void after(){
System.out.println("try中的最后一断码快");
}
@AfterThrowing("pt1()")/*catch*/ //异常通知
public void afterThrowing(){
System.out.println("处理异常中的代码块");
}
@AfterReturning("pt1()") //最终通知
public void afterReturn(){
System.out.println("try catch 之后的代码块");
}
@Around
public Object around(ProceedingJoinPoint pjp){
Object result = null;
try{
System.out.println("before执行前方法");
result = proceedingJoinPoint.proceed();
System.out.println("after执行方法后");
}catch (Throwable e){
System.out.println("after_throwing处理异常");
e.printStackTrace();
} finally {
System.out.println("after_returning最后总要执行的");
}
return result;
}
}
//要增强的类
package com.dcy.srcMethod;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@Component
public class TestAop {
//要增强的方法
public void test() throws Exception {
System.out.println("我的方法");
throw new Exception();
}
}
在spring的配制文件applicationContext.xml中配置,支持aop注解的配置
<aop:aspectj-autoproxy/>
2、配置文件的形式
配置步骤:
- 把通知类交给spring容器来管理,即在spring的配置文件中,设置该类的bean
- 使用aop:config配置AOP配置
- 使用aop:aspect配置切面
- 使用aop:pointcut配置切入点表达式(aop:config中进行配置)
- 使用aop:xxx配置对应的通知类型(在aop:aspect中进行配置)
<!--配置通知-->
<bean id="enhanceMethodManager" class="com.dcy.EnhanceMethodManager"/>
<!--aop配置-->
<aop:config>
<!---切入点配置-->
<aop:pointcut id="pt1" expression="execution(* com.dcy.srcMethod.*.*(..))"/>
<!---切面配置-->
<aop:aspect id="enhanceMethodManagerAdvice" ref="enhanceMethodManager">
<aop:before method="before" pointcut-ref="pt1"/><!--前置通知-->
<aop:after method="after" pointcut-ref="pt1"/><!--后置通知-->
<aop:after-throwing method="afterThrowing" pointcut-ref="pt1"/><!--异常通知-->
<aop:after-returning method="afterReturn" pointcut-ref="pt1"/>!<--最终通知-->
<aop:around method="around" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>