Springboot custom annotation & parameter transfer & simple application

Springboot custom annotation & parameter transfer & simple application

1. Directory structure:

1.1 annotation is a custom annotation position

Insert picture description here
Insert picture description here

2. Custom annotations

2.1 Customize two annotations LogController and TimeConsuming to record logs and time-consuming statistical methods, among which LogController has three parameters

Insert picture description here

@Target({
    
    ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogController {
    
    
    // 具体操作
    String description();

    // 日志级别
    int logLevel() default LogLevelConstant.INFO;

    // 日志进程/方法名
    String method();
}

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

3. Use of annotations

3.1 Use annotations on methods that require logging and time-consuming statistical methods

 	@PostMapping("/createUser")
    @LogController(description = "创建用户", method = "/createUser")
    @TimeConsuming
    public ResponseEntity<ResponseResultVO> createUser(@Valid @RequestBody SysUsersVo sysUsersVo) {
    
    
        log.info("UserManager = start create user [{}] pwd [{}]", sysUsersVo.getUserName(), sysUsersVo.getUserPwd());

        return ResponseEntity.ok(usersService.createUser(sysUsersVo).orElse(ResponseResultVO.builder()
                .code(ErrorCodeConstant.SYSTEM_ERROR)
                .msg(ErrorMsgConstant.SYSTEM_ERROR)
                .build()));
    }

4. Use Aspect to implement functions

4.1 Through Aop, use annotations as a point-cut method to realize business functions

Insert picture description here

	@Pointcut("@annotation(com.pet.annotation.LogController)")
    public void annotationPoint() {
    
    
    }

    @Pointcut("@annotation(com.pet.annotation.TimeConsuming)")
    public void methodTimePoint() {
    
    
    }

4.2 Take the parameters in the annotation

For example, the following method implements the logging function

    @Before(value = "annotationPoint() && @annotation(logController)", argNames = "joinPoint, logController")
    public void beforeController(JoinPoint joinPoint, LogController logController) {
    
    
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        HttpSession session = request.getSession();
        SysUsers user = (SysUsers) session.getAttribute(HttpConstant.SESSION_USER);
        String realMethodName = joinPoint.getSignature().getName();

        log.info("Aspect = [{}] ,user [{}] , method [{}] , logLevel [{}] , do [{}] , realMethod [{}]",
                new Date(), user == null ? "system" : user.getUserName(), logController.method(), logController.logLevel(), logController.description(), realMethodName);

        // 异步处理日志
        publisher.publishEvent(new LogToDbEvent(
                LogToDbEventEntity.builder()
                        .date(new Date())
                        .userName(user == null ? "system" : user.getUserName())
                        .method(logController.method())
                        .logLevel(logController.logLevel())
                        .description(logController.description())
                        .realMethod(realMethodName)
                        .build()));
    }

Statistical method time-consuming method

	@Around(value = "methodTimePoint()")
    public Object apiTimeConsuming(ProceedingJoinPoint pjp) throws Throwable {
    
    
        long begin = System.currentTimeMillis();
        String method = pjp.getSignature().getName();
        String className = pjp.getTarget().getClass().getName();

        Object ret = pjp.proceed();
        log.info("Aspect = [{}] ,class [{}] , method [{}] , time consuming[{}]", new Date(), className, method, System.currentTimeMillis() - begin);
        return ret;
    }

Guess you like

Origin blog.csdn.net/weixin_38045214/article/details/114967252