Spring AOP 中 @Aspect 简单用法

 

package com.ximalaya.business.pay.fee.query.tool.p2.anotationtest;

import org.springframework.stereotype.Component;

/**
 * @author 
 * @date 2019/10/22 下午7:07
 */
@Component
public class NoBug {


    public NoBug() {
        System.out.println(this.toString());
    }

    @Jiecha
    public void suanShu() {
        System.out.println("1234567890");
    }

    @Jiecha
    public void jiafa() {
        System.out.println("1+1=" + 1 + 1);
    }

    @Jiecha
    public void jianfa() {
        System.out.println("1-1=" + (1 - 1));
    }

    @Jiecha
    public void chengfa() {
        System.out.println("3 x 5=" + 3 * 5);
    }

    @Jiecha
    public void chufa() {
        System.out.println("6 / 0=" + 6 / 0);
    }

    public void ziwojieshao() {
        System.out.println("我写的程序没有 bug!");
    }

    @Jiecha2
    public void testWithArgs(String a, int b) {
        System.out.println(a + " is " + b + " years old !");
    }

}
Aspect:
package com..busines.query.tool.p2.anotationtest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author 
 * @date 2019/10/23 上午9:55
 */
@Component
@Aspect
public class AspectMoni {
//AspectMoni不能同时被Component扫描,因为xml也会注入一次,如果被扫描相当于生成两个aop代理,会执行两次,这两处只能注入一处,形成一个代理实例。

    private static Logger logger = LoggerFactory.getLogger(AspectMoni.class);

    public AspectMoni() {
        System.out.println("construct AspectMoni.");
    }

    //切点表达式  *任意返回类型 ..任意匹配 .* 任意方法 (..)任意参数
    @Pointcut("execution(* com.business.query.tool.p2.anotationtest.NoBug.ziwojieshao(..))")
    public void cut() {

    }

    @Around("cut()")
    public Object realCut(ProceedingJoinPoint jp) throws Throwable {

        logger.info("start");
        try {
            jp.proceed();
        } catch (ArithmeticException ae) {
            logger.error("ArithmeticException :" + ae.getMessage());
            throw ae;
        } catch (Exception e) {
            logger.error("Exception :" + e.getMessage());
            throw e;
        }
        logger.info("end");

        return null;
    }

}

单元测试:

@Test
    public void testC() throws Exception {
        
        //测试aspect拦截器
        noBug.ziwojieshao();
        noBug.chengfa();
    }

 

End!

 

ref:

https://blog.csdn.net/shengzhu1/article/details/81271409#commentBox

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值