SpringBoot Controller 自定义注解

引言

想点做点的,一直也没完善,今天加了点东西,比如说/User/AddUser为新增用户,我想把所有的控制器集中起来,做权限管理,下面的demo是把所有的控制器写入到数据库。当然,如果想扩展,通过反射,也是可以很轻松的实现的。

代码

注解的定义

package top.zunmx.csm.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.METHOD})
public @interface Permission {
    String comment() default "";
}

启动触发器

package top.zunmx.csm.annotation;

import jakarta.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import top.zunmx.csm.services.PermissionService;
import top.zunmx.csm.utils.algorithm.MD5Utils;

import java.util.Map;
import java.util.logging.Logger;

@Component
public class AnnotationHandler implements ServletContextAware {
    @Autowired
    private RequestMappingHandlerMapping handlerMapping;
    @Autowired
    private PermissionService permissionService;
    private final Logger logger = Logger.getLogger("PermissionAnnotationHandler");

    public void permissionRegister() {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            Permission annotation = AnnotationUtils.findAnnotation(entry.getValue().getMethod(), Permission.class);
            if (null != annotation) {
                String parent = "undefined";
                Permission parentAnnotation = AnnotationUtils.findAnnotation(entry.getValue().getBeanType(), Permission.class);
                if (parentAnnotation != null) {
                    parent = parentAnnotation.comment();
                }
                String methods = ((RequestMethod) entry.getKey().getMethodsCondition().getMethods().toArray()[0]).name();
                String route = (String) entry.getKey().getPatternValues().toArray()[0];
                String comment = annotation.comment();
                top.zunmx.csm.pojo.Permission permission = new top.zunmx.csm.pojo.Permission();
                permission.setMid(MD5Utils.encode(methods + ":" + route));
                permission.setUrl(route);
                permission.setParent(parent);
                permission.setMethod(methods);
                permission.setFunc_comment(comment);
                permissionService.AddPermission(permission);
//                System.out.println(methods + "::" + route + "::" + comment);
            }
        }
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        permissionRegister();
    }
}

控制器

@Permission(comment = "用户相关")
@RequestMapping("/user")
@RestController
public class UserController {
    @Permission(comment = "获取当前用户名")
    @GetMapping("whoami")
    public ResponseBodyVO whoami() {
        return ResponseBodyVO.success(EnumResponseType.SUCCESS_OK.getCode(), EnumResponseType.SUCCESS_OK.getDesc(), SecurityContextHolder.getContext().getAuthentication().getName());
    }

    @Permission(comment = "获取当前用户所有权限")
    @GetMapping("getPermissions")
    public ResponseBodyVO getPermission() {
        return ResponseBodyVO.success(EnumResponseType.SUCCESS_OK.getCode(), EnumResponseType.SUCCESS_OK.getDesc(), SecurityContextHolder.getContext().getAuthentication().getName());
    }
}

image.png

结语

其它工具类我就不往里面写了,总结一下。

implements ServletContextAware 为了确保Servlet注册完成

Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods(); 获取注册的控制器

for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) 遍历那些方法

AnnotationUtils.findAnnotation(entry.getValue().getMethod(), Permission.class) 判断是否存在这个注解

以上

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。