1、将业务逻辑和切面类要放到Spring容器中,并且注明哪个是切面类(@Aspect);
2、切面类上的通知方法标注通知注解,告诉Spring何时何地运行(@Pointcut("execution()"));
3、开启基于注解的AOP模式(@EnableAspectJAutoProxy)。
@EnableAspectJAutoProxy @Configuration public class MainConfigAop { @Bean public MathCal mathCal() { return new MathCal(); } @Bean public LogAspect logAspect() { return new LogAspect(); } }
public class MathCal { public int div(int i, int j) { System.out.println("mathCal.div"); return i/j; } }
@Aspect public class LogAspect { @Pointcut("execution(public int com.yyc.bean.MathCal.*(..))") public void pointCut() { } @Before("pointCut()") public void methodStart(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); System.out.println(joinPoint.getSignature().getName()+"除法开始。。。参数列表为{"+ Arrays.asList(args)+"}"); } @After("pointCut()") public void methodEnd(JoinPoint joinPoint) { System.out.println(joinPoint.getSignature().getName()+"除法结束。。。"); } @AfterReturning(value = "pointCut()", returning = "result") public void methodReturn(Object result) { System.out.println("除法返回。。。"+result); } @AfterThrowing(value = "pointCut()", throwing = "exception") public void methodException(Exception exception) { System.out.println("除法异常。。。"+exception); } }
div除法开始。。。参数列表为{[1, 1]}
mathCal.div
div除法结束。。。
除法返回。。。1