标题:
Spring 学习笔记(7)
[打印本页]
作者:
look_w
时间:
2019-5-13 13:39
标题:
Spring 学习笔记(7)
Spring 的 AOP 基于 AspectJ 注解开发
开发步骤
引入jar包
设置配置文件:
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
编写配置目标类
<bean id="orderDao" class="demo1.OrderDao"></bean>
public class OrderDao {
public void save(){
System.out.println("save order");
}
public void update(){
System.out.println("update order");
}
public void delete(){
System.out.println("delete order");
}
public void find(){
System.out.println("find order");
}
}
开启aop注解自动代理
<aop:aspectj-autoproxy/>
编写切面类并配置
@Aspect
public class MyAspectAnno {
@Before(value="execution(* demo1.OrderDao.save(..))")
public void before(){
System.out.println("before");
}
}
<bean id="myAspect" class="demo1.MyAspectAnno">
注解通知类型
@Before: 前置通知
@AfterReturning: 后置通知
@AfterReturning(value="execution(* demo1.OrderDao.save(..))",returning="result")
public void after(Object result){
System.out.println("after "+result);
}
@Around:环绕通知
@Around(value="execution(* demo1.OrderDao.save(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("before");
Object obj=joinPoint.proceed();
System.out.println("after");
return obj;
}
@AfterThrowing: 抛出异常
@AfterThrowing(value="execution(* demo1.OrderDao.save(..))",throwing="e")
public void afterThrowing(Throwable e){
System.out.println("exception:"+e.getMessage();
}
@After: 最终通知
@After(value="execution(* demo1.OrderDao.save(..))")
public void after(){
System.out.println("finally");
}
@PointCut:切入点注解
@PointCut(value="execution(* demo1.OrderDao.save(..))")
private void pointcut1(){}
此时,在上述通知的注解中,value可以替换为该函数名,例如:
@After(value="MyAspect.pointcut1()")
public void after(){
System.out.println("finally");
}
这个注解的好处是,只需要维护切入点即可,不用在修改时修改每个注解。
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0