aop通过是否有注解进行切入

 1、注解

package com.common.control;

import java.lang.annotation.*;

/**
 * @date: 2023/6/1 15:44
 * @description: 输出日志
 */
@Documented
@Target({ElementType.METHOD,ElementType.TYPE})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoPrintlnLog {
}

​

2、aop

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;

/**
 * @date: 2023/6/1 15:49
 * @description: 自动输出日志
 */
@Slf4j
@Aspect
@Service
public class AutoPrintlnLogServiceAdvice {

    /**
     *  方法或者类上含有此注解,则会输出请求和返回日志
     */
    @Pointcut("@annotation(com.common.control.AutoPrintlnLog) || @within(com.common.control.AutoPrintlnLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object result;
        //类名
        String className = pjp.getTarget().getClass().getName();
        //方法名
        String methName = pjp.getSignature().getName();
        //参数
        Object[] paramS = pjp.getArgs();
        log.info(className +" "+ methName +" request {}",JSON.toJSONString(paramS));
        result = pjp.proceed();
        log.info(className +" "+ methName +" response {}",JSON.toJSONString(result));
        return result;

    }

}

3、类和方法上添加注解


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 */
@Slf4j
@Controller
@AutoPrintlnLog
public class CloudSignContractRestFacadeImpl {



    @Override
    public Object getBankAndIsSign(Object object) {

    }

    @Override
    public Object sendVerificationCode(Object object) {
    }

    @Override
    public Object signTheContract(Object object) {
    }

}

你可能感兴趣的:(java,spring,mybatis)