一.AOP:aspect oriented programming 面向切面编程
实现的功能:动态的增强一个方法(先拦截该方法,再增强),可以在方法执行的各个阶段加入一些另外的方法来增强原有的方法。
二.概念:
1.横切关注点:要动态增强的功能就是关注点,就是增强的代码所在的方法
2.连接点:类中的方法,字段等都可被称为连接点。连接点都有可能被动态增强,即可以被切断,变成切点
3.切入点:要被拦截的方法,具体要被增强的连接点
4.切面:切入点+通知+增强
5.通知:往被拦截的方法中增强的代码的执行时机
前置通知:在方法执行前执行
后置通知:在方法执行后执行
异常通知:在执行过程中,如果抛出异常后执行
返回通知:在后置之前执行
环绕通知:在方法执行前和执行后执行
6.目标对象:增强代码的所在类
7.织入:将切面应用到目标对象的过程
三.体现在spring中的具体配置:
<aop:config> <!--aop配置-->
<aop:aspect id=“该配置的id” ref=“目标对象所在的bean的id,即增强的代码所在的类的id”> 切面
<aop:pointcut id=“切点的id” expression="execution() 切入表达式,可用通配符匹配多个切点” />
<!--切入点表达式示例execution(* com.xxx.HelloWorld.*(..)) -->
<!--表示com.xxx.HelloWorle类中的所有类型的方法,(..)表示所有类型的参数列表-->
<aop:before method=“目标对象的方法名,即增强代码所在的方法” pointcut-ref=“引用切点的id” /><!--前置通知-->
<aop:after method="目标对象的方法名,即增强代码所在的方法" pointcut-ref=“引用切点的id” /> <!--后置通知-->
</aop:aspect>
</aop:config>
每增加一个目标对象,就要多一个 aop:config aop配置
四.注解的spring AOP
目标对象类:
@Aspect //目标对象类上加入切面注解
public class AspectAop {
//配置切点,里面的value是切入点表达式,这个切点下面对应的pointcut方法只是起到一个id的作用
@Pointcut("execution (* com.lilin.maven.service.annotationaop.UserService.addUser(..))")
public void pointcut() {
}
//配置前置通知,里面的value是上面的切入点注解对应的pointcut方法名,表示这个前置通知作用与pointcut方法上的注解中的切入点
@Before("pointcut()")
public void doBefore() {
System.out.println("doBefore advice");
}
//返回通知
@AfterReturning("pointcut()")
public void doAfterReturning() {
System.out.println("doAfterReturning advice");
}
//后置通知
@After("pointcut()")
public void doAfter() {
System.out.println("doAfter advice");
}
//异常通知
@AfterThrowing("pointcut()")
public void doAfterThrowing() {
System.out.println("doAfterThrowing advice");
}
//环绕通知
@Around("pointcut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("doAround advice start");
Object result = pjp.proceed();
System.out.println("doAround advice end");
return result;
}
}
五.关于通知的五种类型
try
{
// 执行前置通知;
// 执行目标方法;
// 执行返回通知;
}
catche(Exception e)
{
// 执行异常通知;
}
finally
{
// 执行后置通知;
}
本文参考:
https://www.cnblogs.com/GIRLANDBOYS/p/7637673.html
https://www.cnblogs.com/lilin0719/p/5169164.html
http://www.imooc.com/qadetail/75298