springBoot中使用自定义注解

我的项目中全部采用的是注解配置+yml,没使用xml,大同小异而已

1:

/**
 * @author: wzx
 * @Date: 2019/11/9
 * @Description:
 */
@Configuration
@ComponentScan("com.test.constant")
@EnableAspectJAutoProxy//开启AspectJ注解
public class CustomAopConfigurer {
}

spring boot中此项的默认就是开启,所以此项可有可无

2:创建注解类



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)
public @interface ApiLog {
    /**
     * default extension name
     */
    String name() default "张三丰";

    int age() default 12;
}

3:创建切面处理类

​


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author: wzx
 * @Date: 2019/11/9
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class MyApiLog {

//     2. PointCut表示这是一个切点,@annotation表示这个切点切到一个注解上,后面带该注解的全类名
//     切面最主要的就是切点,所有的故事都围绕切点发生
//     logPointCut()代表切点名称
    @Pointcut("@annotation(com.test.constant.ApiLog)")
    public void logPointCut(){};

    @Before("logPointCut()")
    public void before(JoinPoint joinPoint) throws Throwable {
        log.info("@@@@@@@@@@@@@@@PersonAspect ==> before method : {}", joinPoint.getClass());

    }

    @After("logPointCut()")
    public void after(JoinPoint joinPoint){
        log.info("@@@@@@@@@@@@@@@@PersonAspect ==> after method : {}", joinPoint.getClass());
    }

    /**
     * 3. 环绕通知
     * 此处有两种配置
     * 1:@Around("logPointCut()")  前提是上边创建切点
     * 2:@Around(("@annotation(ApiLog)")) 直接注入创建的注解名字 = @interface 的名字
      */
//    @Around("logPointCut()")
    @Around(("@annotation(LxsyApiLog)"))
    public void logAround(ProceedingJoinPoint joinPoint){
        // 获取方法名称
        String methodName = joinPoint.getSignature().getName();
        // 获取入参
        Object[] param = joinPoint.getArgs();

        StringBuilder sb = new StringBuilder();
        for(Object o : param){
            sb.append(o + "; ");
        }
        log.info("#########################################################");
        log.info("进入[" + methodName + "]方法,参数为:" + sb.toString());
        log.info("#########################################################");


        System.out.println("进入[" + methodName + "]方法,参数为:" + sb.toString());

        // 继续执行方法
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        log.info("#########################################################");
        log.info("方法执行结束~~~~~~~~~~~~~~~~~~~~~");
        log.info("#########################################################");
        System.out.println(methodName + "方法执行结束");

    }
}

​

使用自定义注解时需要注意,在使用的类中必须是被spring管理的bean,若直接new 不会生效。

你可能感兴趣的:(java)