spring自定义注解
使用spring自定义注解实现权限访问
1. 首先定义注解类
2. 使用拦截器实现注解功能
3. 配置拦截器
4. 在controller层使用注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {
/**
* 资源key
* */
String value();
}
import com.annotation.demo.annotation.Permission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PermissionInterceptor implements HandlerInterceptor {
/**
* 处理器处理之前调用
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
//在方法上寻找注解
Permission permission = handlerMethod.getMethodAnnotation(Permission.class);
if (permission == null) {
//在类上寻找注解
permission = handlerMethod.getBeanType().getAnnotation(Permission.class);
}
//如果没有添加权限注解则直接跳过允许访问
if (permission == null) {
return true;
}
//获取注解中的值
String value = permission.value();
if ("admin".equals(value)) {
return true;
}
return false;
}
}
import com.annotation.demo.interceptor.PermissionInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
/**
* 注册自定义拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PermissionInterceptor()).addPathPatterns("/api/**");
}
}
package com.annotation.demo.controller;
import com.annotation.demo.annotation.Permission;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author : spiderman
* @version : 1.0
* @FileName : com.annotation.demo
* @Description :
* @Create Date : 2022/1/5 00:24
**/
@RestController
public class TestController {
/**
* 权限为admin才能访问
* @return
*/
@RequestMapping("/api/test")
@Permission(value = "admin")
public String test() {
return "hello world";
}
/**
* 权限为test2才能访问
* @return
*/
@RequestMapping("/api/test2")
@Permission(value = "test2")
public String test2() {
return "hello world";
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!