美文网首页
springboot-AOP

springboot-AOP

作者: inke | 来源:发表于2017-07-07 18:37 被阅读71次

    AOP

    [toc]

    创建切面方式一:

    @Aspect
    @Component
    public class HttpAspect {
        
        
       @Before("execution(public * com.example.HelloController.*(..))")
       public void logBefore() {
           System.out.print("logBefore");
       }
        
        
       @After("execution(public * com.example.HelloController.*(..))")
       public void logAfter() {
           System.out.print("logAfter");
       }
    }
    

    创建切面方式二:(抽取切点出来,减少重复代码)

    @Aspect
    @Component
    public class HttpAspect {
        
       @Pointcut("execution(public * com.example.HelloController.*(..))")
       public void log() {
        
       }
        
       @Before("log()")
       public void logBefore() {
           System.out.print("logBefore");
       }
        
        
       @After("log()")
       public void logAfter() {
           System.out.print("logAfter");
       }
    }
    
    @Aspect
    @Component
    public class HttpAspect {
    
        public static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
    
        @Pointcut("execution(public * com.example.HelloController.*(..))")
        public void log() {
    
        }
    
        @Before("log()")
        public void logBefore(JoinPoint joinPoint) {
            logger.info("logBefore");
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            logger.info("url={}", request.getRequestURL());
            logger.info("method={}", request.getMethod());
            logger.info("ip={}", request.getRemoteAddr());
            logger.info("class.method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            logger.info("args={}", joinPoint.getArgs());
        }
    
    
        @After("log()")
        public void logAfter() {
            logger.info("logAfter");
        }
    
        @AfterReturning(returning = "object", pointcut = "log()")
        public void logAfterReturning(Object object) {
            logger.info("response={}", object.toString());
        }
    }
    
    
    输出日志:
    
    logBefore
    url=http://localhost:8080/updatePerson
    method=PUT
    ip=0:0:0:0:0:0:0:1
    class.method=com.example.HelloController.updatePerson
    args=10
    m person person0_ where person0_.id=?
    logAfter
    response=com.example.Person@34b98c82
    

    相关文章

      网友评论

          本文标题:springboot-AOP

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