Spring AOP使用介绍

2020-12-03  本文已影响0人  向梦而来

在讲解Spring Aop原理之前,需要先了解下如何使用Spring Aop。
举例:打印方法出入口日志

添加xml配置

<aop:aspectj-autoproxy/>

注解

//打印方法出入口日志
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface AccessLog {
    /**
     * 自定义前缀
     * @return
     */
    String preLog() default "";
}

日志切面

@Aspect
@Component
public class AccessLogAdvice {

    @Around(value = "@annotation(log)")
    public Object invoke(ProceedingJoinPoint pjp, AccessLog log){
        String className = pjp.getSignature().getDeclaringType().getSimpleName();
        String method = ((MethodSignature)pjp.getSignature()).getMethod().getName();
        String preLog = log.preLog();
        Object[] args = pjp.getArgs();
        System.out.println(preLog+" className="+className+",methodName="+method+",params="+ JsonUtils.toJson(args));

        Object result = null;
        try {
            result = pjp.proceed();
            System.out.println(preLog+" className="+className+",methodName="+method+",result="+JsonUtils.toJson(result));
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("Exception "+preLog+" className="+className+",methodName="+method+",exception="+throwable);
        }
        return result;
    }
}

接口定义

public interface AdviceFacade {

    Person checkAspectJ(String name);
}

接口实现类

@Service
public class AdviceFacadeImpl implements AdviceFacade {

    @Override
    @AccessLog(preLog = "preCheck")
    public Person checkAspectJ(String name) {
        Person person = new Person();
        person.setName(name);
        person.setAge(18);
        System.out.println("打印信息:"+JsonUtils.toJson(person));
        return person;
    }
}

方法调用打印出入口日志

@RequestMapping("/check")
    public String checkAspectJ(){
        Person person = adviceFacade.checkAspectJ("dyy");
        return "checkAspectJ:"+ JsonUtils.toJson(person);
    }

输出结果

preCheck className=AdviceFacadeImpl,methodName=checkAspectJ,params=["dyy"]
打印信息:{"name":"dyy","age":18}
preCheck className=AdviceFacadeImpl,methodName=checkAspectJ,result={"name":"dyy","age":18}
上一篇下一篇

猜你喜欢

热点阅读