Spring AOP的基于AspectJ注解开发
程序员文章站
2022-07-12 23:07:16
...
一.Spring的AOP的注解开发详细过程
1.编写目标类并配置
这个目标类并没有实现接口,因此spring会自动用Cglib来对其进行动态代理
public class OrderDao {
void add(){
System.out.println("add...");
}
void delete(){
System.out.println("delete...");
}
void update(){
System.out.println("update...");
}
void find(){
System.out.println("find...");
}
}
<!--配置目标类-->
<bean id="OrderDao" class="org.qingyu.dao.OrderDao"></bean>
2.编写切面类并配置
//切面类
public class MyAspect {
public void before(){
System.out.println("前置通知...");
}
}
<!--配置切面类-->
<bean id="MyAspect" class="org.qingyu.aspect.MyAspect"></bean>
3.使用注解对目标类进行增强
//切面类
@Aspect
public class MyAspect {
@Before(value = "execution(* org.qingyu.dao.OrderDao.add(..))")
public void before(){
System.out.println("前置通知...");
}
}
4.编写测试类
public static void main(String[] args){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
OrderDao orderDao = (OrderDao) applicationContext.getBean("OrderDao");
orderDao.add();
}
输出结果如下:
前置通知...
add...
二.Spring的AOP的注解的通知类型
[email protected] 前置通知
@Before(value = "execution(* org.qingyu.dao.OrderDao.add(..))")
public void before(){
System.out.println("前置通知...");
}
[email protected] 后置通知
@AfterReturning(value = "execution(* org.qingyu.dao.OrderDao.delete(..))" ,returning = "result")
public void afterReturning(Object result){
System.out.println("后置通知..."+result);
}
[email protected] 环绕通知
@Around(value = "execution(* org.qingyu.dao.OrderDao.find(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前...");
Object obj = proceedingJoinPoint.proceed();
System.out.println("环绕后...");
return obj;
}
[email protected] 异常抛出通知
@AfterThrowing(value = "execution(* org.qingyu.dao.OrderDao.update(..))",throwing = "e")
public void afterThrowing(Throwable e){
System.out.println("异常抛出通知..."+e.getMessage());
}
三.Spring的注解的AOP的切入点的配置
@After(value = "MyAspect.pointCut1()")
public void after(){
System.out.println("最终通知...");
}
@Pointcut(value = "execution(* org.qingyu.dao.OrderDao.update(..))")
private void pointCut1(){}