美文网首页
Spring AOP使用介绍

Spring AOP使用介绍

作者: 向梦而来 | 来源:发表于2020-12-03 14:28 被阅读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}
    

    相关文章

      网友评论

          本文标题:Spring AOP使用介绍

          本文链接:https://www.haomeiwen.com/subject/ircmwktx.html