SpringAop

一.基于xml的Aop配置

目标类

package com.yqg.aop2;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author yqg
 * @date 2019-02-18 19:36
 */
public class MaJiang {
   
    public void hule(){
        System.out.println("自摸,爽");
    }
}

切面类

package com.yqg.aop2;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @author yqg
 * @date 2019-02-18 19:37
 */
public class Aspect {

    public void before(){
        System.out.println("我听牌了");
    }

    public void after(){
        System.out.println("快给钱");
    }

    public void exception(){
        System.out.println("我诈糊了");
    }

    public void around(ProceedingJoinPoint joinPoint){
        System.out.println("我听牌了啊");
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            System.out.println("我诈糊了啊");
            throwable.printStackTrace();
        }
        System.out.println("快给钱啊");
    }
}

  xml配置

<!--目标对象-->
    <bean id="maJiang" class="com.yqg.aop2.MaJiang"></bean>
    <!--切面对象-->
    <bean id="aspect" class="com.yqg.aop2.Aspect"></bean>

 <aop:config>
<aop:aspect ref="aspect">
<aop:pointcut id="pointcut" expression="execution(* *.hule(..))"></aop:pointcut>
<aop:before method="before" pointcut-ref="pointcut"></aop:before>
<aop:after method="after" pointcut-ref="pointcut"></aop:after>
<aop:after-throwing method="exception" pointcut-ref="pointcut"></aop:after-throwing>
<aop:around method="around" pointcut-ref="pointcut"></aop:around>
</aop:aspect>
</aop:config>

  二.基于注解的Aop配置

package com.yqg.aopannotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * @author yqg
 * @date 2019-02-18 19:37
 */
@Component
@org.aspectj.lang.annotation.Aspect
@EnableAspectJAutoProxy
public class Aspect {
    @Pointcut("execution(* com.yqg.aopannotation.MaJiang.zimo(..))")
    public void pointcut(){}
@Before(value = "pointcut()") public void before(){ System.out.println("我听牌了"); }
@After("pointcut()") public void after(){ System.out.println("快给钱"); }
@AfterThrowing("pointcut()") public void exception(){ System.out.println("我诈糊了"); }
@Around("pointcut()") public void around(ProceedingJoinPoint joinPoint){ System.out.println("我听牌了啊"); try { joinPoint.proceed(); } catch (Throwable throwable) { System.out.println("我诈糊了啊"); throwable.printStackTrace(); } System.out.println("快给钱啊"); } }