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