系列文章目录
实习笔记 —— Spring基础
实习笔记 —— IOC反转控制(xml配置文件 + 注解)
实习笔记 —— AOP开发I
一、AOP中Advice的类型的XML配置文件形式
先回顾昨天学的AOP中的相关术语,体会Advice的含义:
实习时介绍了AOP中Advice的五种类型,我们将这五种类型综合起来学习。
1.before advice前置通知: 在执行切点前的通知,可以判断是否可以执行该切点。
2.after-returning advice后置通知: 在运行完切点完未返回之前,进行通知。
3.around advice环绕通知: 包裹一个方法的执行,这是一个功能强大的通知方式。可以在方法执行前或者执行后around advice,也可以用来判断是否往下执行当前的切点,或者返回切点的值。或者抛出一个异常。
4.after throwing advice异常通知: 在运行完切点时抛出异常进行的通知。
5.After advice最终通知:执行完该切点后,进行的通知。
以具体项目为例:(创建项目第一步先导包)
①声明接口:
②声明接口的实现类:
③创建切面类,将所有新添加的需求对应的方法写在这里:
package com.high.demo1;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
//最开始导错包了import org.aopalliance.intercept.Joinpoint;
// 切面类,存放用户要增加的方法
public class MyAspectXML {
// Advice:通知,增强;甲方要求新增加的方法或需求(如显示用户身份需求)
// public void checkPri() {
// System.out.println("进行身份验证........");
// }
// ctrl + alt + down
// 1.前置通知
public void checkPri(JoinPoint jointJoinpoint) {
System.out.println("save方法的前置通知:进行身份验证........" + jointJoinpoint);
}
// 2.后置通知
public void writeLog(Object result) {
System.out.println("delete方法的后置通知:Be recorded....." + result);
}
// 3.环绕通知:性能监控
// ProceedingJoinPoint是指被增加的接入点find()
public Object aroundOne(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知前.....");
// 调用了此方法对应的切入点 find()方法,基本都要写,用于体现“环绕”
Object proceed = joinPoint.proceed();
System.out.println("环绕通知后前.....");
return proceed;
}
// 4.异常抛出通知
// 参数: Throwable
public void afterThrow(Throwable ex) {
System.out.println("Error appeared." + ex.getMessage());
}
// 5.最终通知 —— 相当于异常中的 finally代码块
public void afterLast() {
System.out.println("This is the final Advice.");
}
}
④编写XML配置文件:
<?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">
<!-- 把ProductDaoImpl类交给spring管理 -->
<!-- 创建目标类 target -->
<bean name="productDao" class="com.high.demo1.ProductDaoImpl">