1.注解方式
<!-- 使用aspetj就是注解-->
<aop:aspectj-autoproxy/>
@Component
@Aspect
public class AspectAop {
/**
* 将所有的pointcut抽到一个方法中
*/
@Pointcut(value = "execution(* com.jjh.service.impl.*.*(..))")
public void pointcut()
{
System.out.println("==pointcut==");
}
/**
* 前置通知
*/
@Before(value = "execution(* com.jjh.service.impl.*.*(..))")
public void before()
{
System.out.println("==before==");
}
/**
* 后置通知(后执行)
*/
@After(value = "execution(* com.jjh.service.impl.*.*(..))")
public void after()
{
System.out.println("==after==");
}
/**
* 后置通知(先执行)
*/
//@AfterReturning(value = "execution(* com.jjh.service.impl.*.*(..))")
// pointcut:pointcut注解的方法名
@AfterReturning(pointcut = "pointcut()")
public void afterReturn()
{
System.out.println("==afterReturn==");
}
/**
* 环绕通知(先执行)
* 参数其实类型是MethodInvocationProceedingJoinPoint(蒙+debug)
* @throws Throwable
*/
@Around(value = "execution(* com.jjh.service.impl.*.*(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
{
System.out.println("==around==" + proceedingJoinPoint);
/* 调用 目标方法 */
try
{
Object obj = proceedingJoinPoint.proceed();
return obj ;
} catch (Throwable e)
{
//e.printStackTrace();
throw e;
}
// return null ;
}
/**
* 异常通知
* throwing:哪些异常需要捕获;
*/
@AfterThrowing(value = "execution(* com.jjh.service.impl.*.*(..))",throwing = "e")
public void afterThrowing(Exception e)
{
System.out.println("==afterThrowing===");
e.printStackTrace();
}
}
2.非注解方式
pointcut:切入点;定义哪些类里面的哪些方法要执行advice
id:唯一,不能重复
expression:表达式,哪些类里面哪些方法执行advice(看房)
execution:执行
();是一个方法的声明;只不过这里面可以使用*表示通配
* com.xyz.myapp..service.*.*(..)
返回值 类名.方法(参数类型 参数的名称)
com.wang.pojo.Dynasty com.wang.service.IService.findOneService():只有这一个方法执行
<bean id="myAfterAdvice" class="com.jjh.aop.MyAfterAdvice" ></bean>
<aop:pointcut id="pointcut" expression="execution(* com.jjh.*.impl.*.*(..))"/>
<aop:advisor advice-ref="myBeforeAdvice" pointcut-ref="pointcut"/>