Board logo

标题: Spring 学习笔记(7) [打印本页]

作者: look_w    时间: 2019-5-13 13:39     标题: Spring 学习笔记(7)

Spring 的 AOP 基于 AspectJ 注解开发开发步骤
<?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: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">
注解通知类型
@AfterReturning(value="execution(* demo1.OrderDao.save(..))",returning="result")
public void after(Object result){
System.out.println("after "+result);
}
@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(value="execution(* demo1.OrderDao.save(..))",throwing="e")
public void afterThrowing(Throwable e){
System.out.println("exception:"+e.getMessage();
}
@After(value="execution(* demo1.OrderDao.save(..))")
public void after(){
System.out.println("finally");
}
@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