@requirespermissions注解_Java反射注解妙用,学会事半功倍文末送书

点击上方[全栈开发者社区]右上角[...][设为星标⭐]

81f13d95a0e004a6d2409db74265d91b.gif

来源:http://rrd.me/epDWH

  • 前言

  • 使用

    • Auth.java

    • UserController.java

    • 主函数

    • 完整的主函数代码


前言

最近在做项目权限,使用shiro实现restful接口权限管理,对整个项目都进行了重构。而权限管理需要用到所有的接口配置,包括接口url地址,接口唯一编码等。想要收集所有的接口信息,如果工程接口很多,工作量可想而知。

这里用了反射,来获取所有接口的信息,接口再多,也不过几秒钟的事。

使用

Auth.java

接口信息对象

主要包括授权地址,权限唯一标识,权限名称,创建时间,请求方式

package com.wwj.springboot.model;

import java.io.Serializable;
import java.util.Date;

public class Auth implements Serializable {

    private String authName;
    private String authUrl;
    private String authUniqueMark;
    private Date createTime;
    private String methodType;

    //get set 省略
}

UserController.java

用户接口,用于测试的接口。

这里使用了标准的restful接口风格,swagger自动API接口,shiro 接口权限注解@RequiresPermissions组合成的一个controller。当然也可以使用其他技术,只要能获取到接口信息就行。

注解不重要,重要的是注解里的信息。

package com.wwj.springboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/users")
@Api(value = "用户管理", tags = {"用户管理"})
public class UserController {

    @GetMapping
    @ApiOperation("获取列表")
    @RequiresPermissions("user:list")
    public void list() {
        System.out.println();
    }


    @GetMapping(path = "/{userId}")
    @ApiOperation("获取详情")
    @RequiresPermissions("user:get")
    public void getUserById(@PathVariable("userId") String userId) {
        System.out.println();
    }

    @PostMapping
    @ApiOperation("新增一个用户")
    @RequiresPermissions("user:save")
    public void save() {
        System.out.println();
    }

    @PutMapping("/{userId}")
    @ApiOperation("修改保存")
    @RequiresPermissions("user:update")
    public void editSave(@PathVariable String userId) {
        System.out.println();
    }

}

主函数

这里通过反射,获取了UserController的所有接口的说明,并存入数据库中。这是最主要的类。

1.设置扫描的package路径

Reflections reflections =
    new Reflections(new ConfigurationBuilder().
    setUrls(ClasspathHelper.
    forPackage(scanPackage)).
    setScanners(new MethodAnnotationsScanner()));

2.获取到扫描包内带有@RequiresPermissions注解的所有方法集合

Set methods = reflections.getMethodsAnnotatedWith(RequiresPermissions.class);

3.通过反射获取类上的注解

method.getDeclaringClass().getAnnotation(RequestMapping.class);

4.通过反射获取方法上的注解

method.getAnnotation(PutMapping.class);

5.获取注解中的某个属性(这里是获取value属性)

method.getAnnotation(PutMapping.class).value();

完整的主函数代码

package com.wwj.springboot;

import com.alibaba.fastjson.JSON;
import com.wwj.springboot.model.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


public class AnnoTest {

    public static void main(String[] args) {
        getRequestMappingMethod("com.wwj.springboot.controller");
    }

    /**
     * @param scanPackage 需要扫描的包路径
     */
    private static void getRequestMappingMethod(String scanPackage) {
        //设置扫描路径
        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(scanPackage)).setScanners(new MethodAnnotationsScanner()));

        //扫描包内带有@RequiresPermissions注解的所有方法集合
        Set methods = reflections.getMethodsAnnotatedWith(RequiresPermissions.class);List list = new ArrayList<>();
        Date now = new Date();//循环获取方法
        methods.forEach(method -> {//用于保存方法的请求类型String methodType = "";//获取类上的@RequestMapping注解的值,作为请求的基础路径String authUrl = method.getDeclaringClass().getAnnotation(RequestMapping.class).value()[0];//获取方法上的@PutMapping,@GetMapping,@PostMapping,@DeleteMapping注解的值,作为请求路径,并区分请求方式if (method.getAnnotation(PutMapping.class) != null) {
                methodType = "put";if (method.getAnnotation(PutMapping.class).value().length > 0) {
                    authUrl = method.getAnnotation(PutMapping.class).value()[0];
                }
            } else if (method.getAnnotation(GetMapping.class) != null) {
                methodType = "get";if (method.getAnnotation(GetMapping.class).value().length > 0) {
                    authUrl = method.getAnnotation(GetMapping.class).value()[0];
                }
            } else if (method.getAnnotation(PostMapping.class) != null) {
                methodType = "post";if (method.getAnnotation(PostMapping.class).value().length > 0) {
                    authUrl = method.getAnnotation(PostMapping.class).value()[0];
                }
            } else if (method.getAnnotation(DeleteMapping.class) != null) {if (method.getAnnotation(DeleteMapping.class).value().length > 0) {
                    authUrl = method.getAnnotation(DeleteMapping.class).value()[0];
                }
            }//使用Auth对象来保存值
            Auth auth = new Auth();
            auth.setMethodType(methodType);
            auth.setAuthUniqueMark(method.getAnnotation(RequiresPermissions.class).value()[0]);
            auth.setAuthUrl(authUrl);
            auth.setAuthName(method.getDeclaringClass().getAnnotation(Api.class).value() + "-" + method.getAnnotation(ApiOperation.class).value());
            auth.setCreateTime(now);
            list.add(auth);
        });//TODO 输出到控制台,此处存数据库即可
        System.out.println(JSON.toJSONString(list));
    }
}

通过上面所说的方法即可获取到注解中的值,这样就可以获取到我们想要的接口信息了,执行结果如下

[{"authName":"用户管理-获取详情","authUniqueMark":"user:get","authUrl":"/users","createTime":1540977757616,"methodType":"get"},
{"authName":"用户管理-新增一个用户","authUniqueMark":"user:save","authUrl":"/users","createTime":1540977757616,"methodType":"post"},
{"authName":"用户管理-修改保存","authUniqueMark":"user:update","authUrl":"/{userId}","createTime":1540977757616,"methodType":"put"},
{"authName":"用户管理-获取列表","authUniqueMark":"user:list","authUrl":"/users","createTime":1540977757616,"methodType":"get"}]

推荐:《Python 3.x基础教程》

5313dca230aaaead539d4238856337a1.png

编辑推荐:Python入门经典,含6大特色:Python功能全面讲解+技术深入剖析+案例同步训练+上机实战+教学资料+32小时全程同步教学视频!

如何购买:点击链接或阅读原文了解更多。。。

该书参与了当当“程序员节”活动,每满100减50哟~

全栈读者福利:

当当20周年,每满100减50,全栈开发者社区独家优惠码RNVDAD(付款时使用),在每满100减50的基础上可满200减30,活动截止时间是11月1日。

觉得本文对你有帮助?请分享给更多人

关注「全栈开发者社区」加星标,提升全栈技能

本公众号会不定期给大家发福利,包括送书、学习资源等,敬请期待吧!

如果感觉推送内容不错,不妨右下角点个在看转发朋友圈或收藏,感谢支持。

好文章,我在看❤️

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值