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";
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM