Spring AOP Annotaion

本文介绍如何使用Spring AOP进行面向切面编程,通过注解方式实现日志拦截器,展示了不同类型的Advice如@Before、@AfterThrowing等,并解释了它们的执行时机。

aop Spring Annotaion

  1. 将下面的标签加入Spring的xml中(注意添加对应的scama)
  2. aop的好处:可以动态的添加或删除切面上的逻辑,而不影响原代码的执行
    a) filter
    b) struts2的interceptor
/**
 * Created by liudy on 17/4/16.
 * Aspect-Oriented-Programming
 * 面向切面编程,是对面向对象的思维方式的有力补充
 * 如果被代理的对象没有实现接口,那么spring aop会使用CGLIB来产生动态代理的对象,那么需要添加相应的jar包
 * 如果实现了接口,会使用jdk来产生动态代理对象
 */
@Aspect
@Component
public class LogInterceptor {
    /* 概念 了解即可
    1. JoinPoint(连接点  加入切面逻辑的点,比如某方法之前  )
    2. PointCut(JointPoint的集合
       execution(* com.baobaotao.dao.*.*(..)) )
    3. Aspect(切面)
       简单认为切面类中的逻辑(方法),为切面
    4. Advice(加在切入点上的建议)
       例如@Before  @After等
    5. Target
       被代理对象
    6. Weave
       织入

     */

    @Pointcut("execution(public * com.baobaotao.dao..*.*(..))")
    public  void myMethod(){

    }

    // execution  是指方法的执行   是最常见的   还可切到属性上等等,但不常见
    @Before("myMethod()")
    public void before(){
        System.out.println("method start");
    }

    // 在被代理对象的方法抛异常之后
    @AfterThrowing("execution(public void com.baobaotao.dao.LoginLogDao.insertLoginLog(com.baobaotao.domain.LoginLog))")
    public void afterThrowing(){
        System.out.println("after throwing");
    }

    // 在被代理对象的方法正常返回后执行
    @AfterReturning("execution(public void com.baobaotao.dao.LoginLogDao.insertLoginLog(com.baobaotao.domain.LoginLog))")
    public void afterReturning(){
        System.out.println("method AfterReturning");
    }

    //  在被代理对象方法的try-catch后,即finally时执行
    @After("execution(public void com.baobaotao.dao.LoginLogDao.insertLoginLog(com.baobaotao.domain.LoginLog))")
    public void after(){
        System.out.println("after");
    }

    @Around("myMethod()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println(" method around start");
        pjp.proceed();
        System.out.println(" method around end");

    }

    //  PointCut  连接点的集合   com.baobaotao.dao包及子包(..)中,任何类的任何方法
    @Before("execution(public * com.baobaotao.dao..*.*(..))")
    public void before1(){
        System.out.println("save start");
    }

    // 除excution外(aspectj实现的)  Spring自身也提供了织入点语法  例如within  this  target等  但不常用

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值