0
点赞
收藏
分享

微信扫一扫

Spring-aop-Before/After/Around/Advisor与Pointcut接口的代码示例


Advisor:它是标注有@Before@After@Around注解的方法的抽象
Pointcut:无论这个Pointcut是接口,还是注解,它抽象的都是带有execution表达式的东西

下面有这样一段代码,我们可以说MyAspect这个类中
有2个Advisor,分别是aa和bb
有2个Pointcut,分别是​​​* com.abc.*.*(..)​​​和​​* com.xx包.*.*(..)​

@Configuration
@Aspect
@EnableAspectJAutoProxy
public class MyAspect {
@Before("execution(* com.abc.*.*(..))")
public void aa() {
System.out.println("你叫什么名字?");
}

@Before("execution(* com.xx包.*.*(..))")
public void bb() {
System.out.println("你叫什么名字?");
}
}

下面是使用效果

package study.ssm.temp;

public class MyUser {
public void sayName() {
System.out.println("我叫二抱,它叫三抱");
}

public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyUser.class, MyAspect.class);
MyUser user = ctx.getBean(MyUser.class);
user.sayName();
}
}

package study.ssm.temp;

@Aspect
@EnableAspectJAutoProxy
public class MyAspect {
@Before("execution(* study..*.*(..))")
public void aa() {
System.out.println("你们叫什么名字呀?");
}
}

@AfterReturning 打印返回值
有时候我们需要打印一个方法的返回值,那么可以使用该注解,方式如下

@Pointcut("execution(* com.abc.*.*(..))")
public void pointcutDeclaration() {
// NOOP
}

// 注意:returning的参数名必须和方法printLog里的参数名称一样,如果returning = "abc",那么printLog(Object abc)
@AfterReturning(value = "pointcutDeclaration()", returning = "returnValue")
public void printLog(Object returnValue) {
log.info("返回值:{}", JSON.toJSONString(returnValue));
}

彩色打印,由于服务器上的日志太多了,如果字体能够醒目一些,那就太好了,你可以如下一波操作

String msg= "\33[34m" + "日志内容" + "\33[0m";
log.info("\33[32m参数:{}", msg);
// System.log.println("\33[32m"+"绿色的内容"+"\33[34m" + "其他颜色的内容" + "\33[0m");


举报

相关推荐

0 条评论