1. 程式人生 > >小慶的Spring學習筆記三

小慶的Spring學習筆記三

exce ring catch try ace nbsp component 切面 conf

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("快給錢啊"); } }

  

小慶的Spring學習筆記三