2.AOP:面向方面编程
一个普通的类 -> 有特定功能的类
a.继承类 b.实现接口 c.注解 d.配置
public class MyFilter exntends/implements Xx
{
}
类 -> “通知” :实现接口
前置通知实现步骤:
a.jar
aopaliance.jar
aspectjweaver.jar(百科:Aspectj)
b.配置
c.编写
aop:每当之前add()之前 自动执行一个方法log();
addStudent(); 业务方法(IStudentService.java中的 addStudent())
before(); 自动执行的通知,即aop前置通知
public class Xxx
{
@Test
a(){}
}
如果出现异常:类似java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
则说明缺少jar
后置通知:
a.通知类 ,普通实现接口
b.业务类、业务方法
StudentServiceImpl中的addStudent()
c.配置:
将业务类、通知 纳入springIOC容器
定义切入点(一端)、定义通知类(另一端),通过pointcut-ref将两端连接起来
异常通知:
根据异常通知接口的定义可以发现,异常通知的实现类 必须编写以下方法:
public void afterThrowing([Method, args, target], ThrowableSubclass):
a.public void afterThrowing(Method, args, target, ThrowableSubclass)
b.public void afterThrowing( ThrowableSubclass)
环绕通知: 在目标方法的前后、异常发生时、最终等各个地方都可以进行的通知,最强大的一个通知;
可以获取目标方法的全部控制权(目标方法是否执行、执行之前、执行之后、参数、返回值等)
在使用环绕通知时,目标方法的一切信息 都可以通过invocation参数获取到
表达式expression的常见示例如表所示。
expression="execution(…)"
举例 |
含义 |
public boolean addStudent(org.lanqiao.entity.Student)) |
所有返回类型为boolean、参数类型为org.lanqiao.entity.Student的addStudent()方法。 |
public boolean org.lanqiao.service.IStudentService. addStudent(org.lanqiao.entity.Student) |
org.lanqiao.service.IStudentService类(或接口)中的addStudent()方法,并且返回类型是boolean、参数类型是org.lanqiao.entity.Student |
public * addStudent(org.lanqiao.entity.Student) |
“*”代表任意返回类型 |
public void *( org.lanqiao.entity.Student) |
“*”代表任意方法名 |
public void addStudent(..) |
“..”代表任意参数列表 |
* org.lanqiao.service.*.*(..) |
org.lanqiao.service.IStudentService包中,包含的所有方法(不包含子包中的方法) |
* org.lanqiao.service..*.*(..) |
org.lanqiao.service.IStudentService包中,包含的所有方法(包含子包中的方法) |