Spring/Springboot AOP 自定义注解记录日志操作

本文采用的方法是使用注解记录日志,废话不多说直接上干货。

创建一个自定义@Log日志标签

package com.insurance.dao;



import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

    /**方法描述*/
    public String  methodDesc() default "";

}

@Target(ElementType.METHOD)表示标签注解在方法上,@Documented,@Retention(RetentionPolicy.RUNTIME)这2个标签不再解释

创建一个LogAdvice 切面

package com.insurance.dao;
import java.lang.reflect.Method;
import java.math.BigDecimal;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.insurance.dto.PayRequest;
import com.insurance.mapper.ApiChannelLogMapper;
import com.insurance.model.ApiChannelLog;

@Aspect
@Component
public class LogAdvice {
    @Autowired
    private ApiChannelLogMapper apiChannelLogMapper;
    private static final Logger logger=LoggerFactory.getLogger(LogAdvice.class);

    /** 配置切入点 */
    @Pointcut("@annotation(com.insurance.dao.Log)")//切入到@Log标签上
    public void serviceAspect() {
    }

    /**
     * @Description: 后置通知
     */
    @After("serviceAspect()")
    public void after(JoinPoint joinPoint) {
        logger.info("开始记录日志*************************");
        PayRequest payRequest=null;
        try {
            String targetName = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            Object[] arguments = joinPoint.getArgs();
            Class targetClass = Class.forName(targetName);
            Method[] methods = targetClass.getMethods();
            String methodDesc = "";
            String params = "";
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] clazzs = method.getParameterTypes();
                    if (clazzs.length == arguments.length) {

                        if (!method.isAnnotationPresent(Log.class))
                            return;                     
                        methodDesc = method.getAnnotation(Log.class).methodDesc(); // 获取标签注解字段信息                     
                        for (int i = 0; i < arguments.length; i++) {
                            params = params + arguments[i] + (i == arguments.length - 1 ? "" : ","); 
                            // 获取请求参数                         
                        }

                        break;
                    }
                }
            }
            //arguments是Object参数,假如你请求方法传的是PayRequest参数对象
            PayRequest payRequest=PayRequest(params);
            ApiChannelLog apiChannelLog=new ApiChannelLog();
            apiChannelLog.setChannel_client(payRequest.getChannel_client);
            apiChannelLog.setChannel_method(payRequest.getChannel_method);
            apiChannelLog.setCreateTime(payRequest.getCreateTime);
            apiChannelLog.setMerchant_sn(payRequest.getMerchant_sn);
            apiChannelLog.setOrder_no(payRequest.getOrder_no);
            apiChannelLog.setReq(payRequest.getReq);
            apiChannelLogMapper.add(apiChannelLog);
            logger.info("结束记录日志*************************");    
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


}

创建一个TestService,将@Log注入该类方法上

package com.insurance.service.impl;

import org.springframework.stereotype.Service;

import com.insurance.dao.Log;
import com.insurance.dto.PayRequest;

@Service
public class TestService {  
    @Log(methodDesc="日志记录") 
    public void login(PayRequest payRequest) {  
        payRequest.setAppid("1111112");     
    }
}

创建一个控制层


     @RequestMapping("/test")
     @ResponseBody
     public void test(HttpServletResponse response, HttpServletRequest request,HelibaoParam param)throws Exception{
         PayRequest payRequest=new PayRequest();
         payRequest.setMerchantno("12365412");
         payRequest.setUrl("http:www.baidu.com");
         payRequest.setOrderid("1233652");
         testService.login(payRequest);  
         response.getWriter().print("SUCCESS"); 
     }

进行访问

这里写图片描述

这样就能实现一个自定义注解标签AOP记录日志功能

猜你喜欢

转载自blog.csdn.net/qq_35939864/article/details/81774670