Springboot 实战 自定义注解和AOP

77 阅读1分钟

前言

在工作中,经常需要编写一些重复的代码,一旦修改就需要全局搜索一个个的修改,不仅编写的工作量大,修改还容易出错或者遗漏。故而需要一种能够方便扩展,快速插入和管理重复代码的方式。

今天,我要介绍的就是自定义注解+aop的实现方式。
案例:需要对方法的入参进行预处理,添加额外的业务值。

1. 自定义注解

package com.example.testspring.user.annotation;

import java.lang.annotation.*;

@Documented
@Target({ElementType.PARAMETER,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ProcessParam {
    int value() default 0;
}

2. 编写aop

package com.example.testspring.user.aop;

import com.example.testspring.user.annotation.ProcessParam;
import com.example.testspring.user.entity.dto.CommonDTO; 
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before; 
import org.aspectj.lang.reflect.MethodSignature; 
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Method; 

@Slf4j
@Aspect
@Component
public class ParamsAspect {
    @Before("@annotation(processParam)")
    public void preProcess(JoinPoint joinPoint, ProcessParam processParam) throws Throwable {
        Object[] parameters = joinPoint.getArgs();
        Object parameter = parameters[processParam.value()];

        System.out.println("index:"+processParam.value()+", param:"+parameter+","+parameter.getClass());
        if(parameter instanceof CommonDTO){
            ((CommonDTO) parameter).setCorpId("i am corp id");
        }
    }
}

3. 应用自定义注解

package com.example.testspring.user.controller;

import com.example.testspring.user.annotation.ProcessParam;
import com.example.testspring.user.entity.dto.QueryDTO;
import com.example.testspring.user.entity.dto.UserDTO;
import com.example.testspring.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/user/index")
public class IndexController {

    @Autowired
    private Map<String, IUserService> userServiceMap;

    @PostMapping("/hello")
    @ProcessParam
    public Map<String, String> test(@RequestBody @Validated UserDTO userDTO) {
        String name = userDTO.getUserType().getServiceName();
        IUserService userService = userServiceMap.get(name);
        userService.say(); 
        return new HashMap<String, String>() {
            {
                put("username", userDTO.getUsername());
                put("phone", userDTO.getPhone().toString());
                put("corpId", userDTO.getCorpId());
            }
        };
    } 
}

4. 验证

image.png