1. AOP面向切面编程:
(1):相关术语:
①:JoinPoint:连接点:被拦截(代理)的方法;
②:JoinCut:切入点:真正被拦截后增强的方法;
③:Advice:通知:拦截到JoinPoint后所要做的事情:
——分为前置通知、后置通知、异常通知、最终通知和环绕通知。
④:Introduction:引介:可在运行期间为类动态添加一些方法;
⑤:Target:目标:被代理对象;
⑥:Weaving:织入:把增强应用到Target中的来创建新的代理对象的过程;
⑦:Proxy:代理:代理对象;
⑧:Aspect:切面:JoinCut和Advice(Introduction)的调用关系;
(2):XML配置简单AOP:
<bean id="accountService" class="cn.xupt.service.AccountService"></bean>
<!--日志要在账户操作前执行-->
<bean id="logger" class="cn.xupt.utils.Logger"></bean>
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<!--用切面表达式与公共方法建立联系-->
<aop:before method="printLog" pointcut="execution(public void cn.xupt.service.AccountService.saveAccount())"></aop:before>
</aop:aspect>
</aop:config>
(3):切面表达式的写法:
全通配写法:
* *..*.*(..)
第一个*表示返回类型,后面的*..表示当前包和它的子包,再后面的*.*表示类名及方法名,括号内的..表示有无参数均可,参数可以是任意类型。
(4):四种通知的XML配置:
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="beforeLog" pointcut-ref="pt1"></aop:before>
<aop:after-returning method="afterReturningLog" pointcut-ref="pt1"></aop:after-returning>
<aop:after-throwing method="afterThrowingLog" pointcut-ref="pt1"></aop:after-throwing>
<aop:after method="afterLog" pointcut-ref="pt1"></aop:after>
<aop:pointcut id="pt1" expression="execution(* cn.xupt.service.*.*(..))"/>
</aop:aspect>
</aop:config>
(5):环绕通知:是spring提供的一种可以通过修改代码来控制增强方法何时执行的方法。
XML配置:
<aop:config>
<aop:pointcut id="pt1" expression="execution(* cn.xupt.service.*.*(..))"/>
<aop:aspect id="logAdvice" ref="logger">
<aop:around method="arroundLog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
2. AOP的注解配置:
(1):spring注解支持:
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
(2):切面类:
@Aspect //切面类
public class Logger
(3):切面表达式:
@Pointcut("execution(* cn.xupt.service.*.*(..))")
private void pt1(){};
(4):四种通知:
@Before("pt1()")
public void beforeLog(){
System.out.println("前置通知");
}
@AfterReturning("pt1()")
public void afterReturningLog(){
System.out.println("后置通知");
}
@AfterThrowing("pt1()")
public void afterThrowingLog(){
System.out.println("异常通知");
}
@After("pt1()")
public void afterLog(){
System.out.println("最终通知");
}
(5):环绕通知:
@Around("pt1()")
public Object arroundLog(ProceedingJoinPoint pj){
Object rt = null;
try {
System.out.println("环绕通知配置前置通知");
Object[] args = pj.getArgs();
rt = pj.proceed(args);
System.out.println("环绕通知配置后置通知");
}catch (Throwable t){
System.out.println("环绕通知配置异常通知");
t.printStackTrace();
}finally {
System.out.println("环绕通知配置最终通知");
}
return rt;
}
本文详细介绍了AOP(面向切面编程)的基本概念,包括连接点、切入点、通知、引介、目标、织入、代理和切面等关键术语。通过XML配置和注解配置两种方式,阐述了如何在Spring框架中实现AOP,涵盖了前置通知、后置通知、异常通知、最终通知和环绕通知的具体应用。

被折叠的 条评论
为什么被折叠?



