springboot中读取所有添加指定注解的方法

5 篇文章 1 订阅
订阅专栏

springboot中读取所有添加了自定义标签的方法

需求描述

最近公司要求用springSecurity搞一套权限管理(RBAC),单独就tb_permission表数据来说,我需要读取到Controller中所有添加了自定义注解的函数并将其路由存入数据库,需要达到效果如下:

在这里插入图片描述

自定义注解

import java.lang.annotation.*;


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckPermission {
    /**
     * 描述
     *
     * @return
     */
    String descrption() default "" ;
}

测试Controller

import com.dar.road.core.annotation.CheckPermission;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author weiwenbin
 * @Date 2020/5/20 上午9:40
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping("/justTest")
    @CheckPermission(descrption = "测试-只是个测试")
    public void justTest() {
        System.out.println("我只是个测试方法");
    }
}

AnnotationUtil工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * @Author weiwenbin
 * @Date 2020/5/14 下午5:31
 */
@Component
public class AnnotationUtil {
    @Autowired
    private ResourceLoader resourceLoader;

    private static final String VALUE = "value";

    /**
     * 获取指定包下所有添加了执行注解的方法信息
     * @param classPath 包名
     * @param tagAnnotationClass 指定注解类型
     * @param <T>
     * @return
     * @throws Exception
     */
    public  <T> Map<String, Map<String, Object>> getAllAddTagAnnotationUrl(String classPath, Class<T> tagAnnotationClass) throws Exception {
        Map<String, Map<String, Object>> resMap = new HashMap<>();
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources = resolver.getResources(classPath);

        for (org.springframework.core.io.Resource r : resources) {
            MetadataReader reader = metaReader.getMetadataReader(r);
            resMap = resolveClass(reader, resMap, tagAnnotationClass);
        }


        return resMap;
    }

    private <T> Map<String, Map<String, Object>> resolveClass(
            MetadataReader reader, Map<String, Map<String, Object>> resMap, Class<T> tagAnnotationClass)
            throws Exception {
        String tagAnnotationClassCanonicalName = tagAnnotationClass.getCanonicalName();
        //获取注解元数据
        AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
        //获取类中RequestMapping注解的属性
        Map<String, Object> annotationAttributes =
                annotationMetadata.getAnnotationAttributes(RequestMapping.class.getCanonicalName());

        //若类无RequestMapping注解
        if (annotationAttributes == null) return resMap;

        //获取RequestMapping注解的value
        String[] pathParents = (String[]) annotationAttributes.get(VALUE);
        if (0 == pathParents.length) return resMap;

        //获取RequestMapping注解的value
        String pathParent = pathParents[0];

        //获取当前类中已添加要扫描注解的方法
        Set<MethodMetadata> annotatedMethods = annotationMetadata.getAnnotatedMethods(tagAnnotationClassCanonicalName);

        for (MethodMetadata annotatedMethod : annotatedMethods) {
            //获取当前方法中要扫描注解的属性
            Map<String, Object> targetAttr = annotatedMethod.getAnnotationAttributes(tagAnnotationClassCanonicalName);
            //获取当前方法中要xxxMapping注解的属性
            Map<String, Object> mappingAttr = getPathByMethod(annotatedMethod);
            if (mappingAttr == null){
                continue;
            }

            String[] childPath = (String[]) mappingAttr.get(VALUE);
            if (targetAttr == null || childPath == null || childPath.length == 0) {
                continue;
            }

            String path = pathParent + childPath[0];

            boolean isHas = resMap.containsKey(path);
            if (isHas){
                throw new Exception("重复定义了相同的映射关系");
            }

            resMap.put(path, targetAttr);
        }

        return resMap;
    }


    private Map<String, Object> getPathByMethod(MethodMetadata annotatedMethod) {
        Map<String, Object> annotationAttributes = annotatedMethod.getAnnotationAttributes(GetMapping.class.getCanonicalName());
        if (annotationAttributes != null && annotationAttributes.get(VALUE) != null) {
            return annotationAttributes;
        }
        annotationAttributes = annotatedMethod.getAnnotationAttributes(PostMapping.class.getCanonicalName());
        if (annotationAttributes != null && annotationAttributes.get(VALUE) != null) {
            return annotationAttributes;
        }

        annotationAttributes = annotatedMethod.getAnnotationAttributes(DeleteMapping.class.getCanonicalName());
        if (annotationAttributes != null && annotationAttributes.get(VALUE) != null) {
            return annotationAttributes;
        }

        annotationAttributes = annotatedMethod.getAnnotationAttributes(PutMapping.class.getCanonicalName());
        if (annotationAttributes != null && annotationAttributes.get(VALUE) != null) {
            return annotationAttributes;
        }
        annotationAttributes = annotatedMethod.getAnnotationAttributes(RequestMapping.class.getCanonicalName());
        return annotationAttributes;
    }
}

调用

上面做完之后直接调用,获取到map如图, 我这边直接将map做一次处理后直接存库(tb_permission)。
在这里插入图片描述

在这里插入图片描述

Springboot注解读取配置文件自定义配置信息
wilson_m的博客
03-06 3139
springboot项目的配置文件信息一般放在application.yml(也有命名application.properties)文件,当项目启动的时候,我们可以只修改配置文件的配置,而不修改代码。如果不在配置文件配置信息,虽然也可以实现功能,但是容易出现问题。 例如:跨系统交互时,另外一个系统(系统A)的域名或者端口发生变化,我们需要在自己的项目对其地址信息进行修改。如果不在配置文件...
SpringBoot自定义注解
web13116256725的博客
09-10 1162
深知大多数初Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!因此收集整理了一份《Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
获取带有指定注解的所有对象
qq_36816062的博客
11-03 4751
获取带有指定注解的所有对象 最近在项目上需要实现一个功能:项目启动的时候需要获取带有指定注解的所有对象,通过对象去操作方法和属性 一开始也想到了使用反射,自己写的代码有点多,不好扩展,网上一搜,发现有Reflections反射框架,使用起来非常简单 1.引入maven依赖 <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</art
SpringBoot 注解大全(详细)
最新发布
LLLL_JJJJ的博客
09-03 638
来开启一项功能的支持。
java 反射 方法注解_Java利用反射如何查找使用指定注解详解
weixin_39718286的博客
02-12 253
前言最近有些空,想自己写个跟spring里的注解一样的注解来用,然后希望能找到使用了自己写了注解,下面来介绍一下实现方法声明,下面代码是没看过spring源码写的,基本上都是网上找的博客,整理的定义注解Controller.java@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @i...
Spring Boot 注解收集
旧路
09-13 1549
       Spring Boot使用过程,经常需要和很多注解打交道。也是我们常说的注解编程。所以接下来我们对Spring Boot常用注解做一个简单的收集。 一 配置相关注解         配置相关注解 解释 @SpringBootApplication 组合注解,由@SpringBootC...
springboot获取指定包下的包含某个注解的全部
Brave_heart4pzj的博客
08-12 3097
https://www.cnblogs.com/lexiaoyao1995/p/13943784.html
springboot获取某个注解下面的某个方法方法名,参数值等等详细实例
gb4215287的博客
06-21 716
springboot获取某个注解下面的某个方法方法名,参数值等等详细实例
springboot读取自定义配置文件节点的方法
08-27
在上面的代码,我们使用 @PropertySource 注解指定自定义文件的路径,并使用 @ConfigurationProperties 注解指定节点的前缀。然后,我们可以使用 @Autowired 注解获取该实体的实例,并使用其 getter 方法...
springboot 脱敏自定义注解
03-25
`@Target(ElementType.METHOD)`指定注解用于方法。 接下来,我们需要创建一个切面,该将包含处理脱敏逻辑的`@Aspect`注解方法。例如: ```java @Aspect @Component public class DesensitizeAspect { @...
springboot如何读取配置文件(application.yml)的属性值
08-30
使用`@Component`注解创建一个Bean,`@ConfigurationProperties`注解指定了配置前缀,即`myProps`,这样Spring Boot就会自动将配置文件`myProps`下面的属性值注入到这个的相应字段: ```java import org....
SpringBoot读取自定义properties配置文件的方法
08-28
在需要使用`RemoteProperties`的添加`@EnableConfigurationProperties(RemoteProperties.class)`注解,然后使用`@Autowired`自动注入`RemoteProperties`实例,这样就可以访问配置文件的属性了。例如: ```...
Spring获取某个包下带有特定注解的所有的集合
cong__cong__cong的博客
08-16 692
【代码】Spring获取某个包下带有特定注解的所有的集合。
java借助Spring获取所有带有指定注解的接口、、对象-续集
热门推荐
靓仔!——没错!我叫你呢!
11-19 1万+
1、支持通过Spring的xml配置文件来制定要获取注解的包,如何获取配置文件的参数: /** * 通过依赖注入获取配置文件的属性值 * @param basePackages */ @Resource public void setBasePackages(String... basePackages) { this.basePackages = basePackages; } 2、S
springboot读取所有自定义注解
程序员
12-28 2589
先说下需求,是用作权限使用 自定义注解 Permission package org.com.rsmall.wx.ann; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE, E
Spring 自定义注解后,如何获取添加了该注解的所有?终极解答
码农六子
11-08 8074
1、问题需求 通常在业务开发时,我们可能会用到自定义注解(自定义注解的使用和解析,本章暂不介绍)。在使用自定义注解后,我们需要获取使用了该注解的所有,然后做一个验证。那么、问题来了,我们如何获取被某注解标注的所有呢?请欣赏下文: 2、具体实现 2.1、定义两个注解 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface RespMegTypeSup { ...
Springboot扫描指定包含特定注解
sinat_39314995的博客
07-17 3212
package com.**.handler; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.persistence.Table; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolv
spring boot 获取指定自定义注解的内容
09-26 8231
一、获取自定义注解内容: /** * 自定义注解内容获取 * @author Chen,Shunhua * @date 2017年9月26日 上午10:53:39 */ public class RequestLimitUtils { /** * 查询指定controller的功能点信息 * @param clazz: controller名 * @param enable_...
SpringBoot 读取配置文件内容的几种方式
weixin_44138647的博客
01-06 659
读取application文件 在application.yml或者properties文件添加: info.address=USA info.company=Spring info.degree=high @Value注解读取方式 import org.springframework.beans.factory.annotation.Value; import org.springfra...
写文章

热门文章

  • 2019-07高德地图行政区域省市区json数据获取(php代码) 19562
  • Lock wait timeout exceeded; try restarting transaction解决 12714
  • springboot中读取所有添加指定注解的方法 10129
  • mybatis-plus-generator使用mybatisPlus代码生成器生成代码、xmlsql拼接、自定义类 3094
  • springCloud学习-feign 2796

分类专栏

  • springcloud 5篇
  • springboot 5篇
  • activiti 2篇
  • linux 12篇
  • scala 6篇
  • oracle 1篇
  • mysql 1篇
  • symfony 1篇
  • 三方 2篇
  • twig 1篇
  • 其他 3篇
  • java基础 22篇
  • composer 1篇
  • git 3篇
  • php 1篇
  • yii 1篇

最新评论

  • 解决CentOS8中idea无法输入中文、无快捷图标问题

    葵续浅笑: 不能输中文的问题解决了,确实换个jdk就好了,留言感谢

  • springboot中读取所有添加指定注解的方法

    天堂2008: 很实用,感觉分享,按照楼主的分享可以实现的。

  • springboot2---如何用表单模拟Rest风格

    不正经的kimol君: 大佬,我准备跟你混了!

  • centos8安装elasticsearch-7.12.0

    Dlwyz: 抱歉一直没看见 ES_JAVA_HOME 是指向es自带的jdk 你可能是没权限访问这个目录

最新文章

  • springCloud学习-feign
  • springCloud学习-nacos配置管理-配置与拉取、配置热更新、多环境配置、多服务配置共享
  • activiti6 ui搭建
2022年7篇
2021年11篇
2020年12篇
2019年36篇
2017年1篇

目录

目录

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

玻璃钢生产厂家安徽抽象玻璃钢雕塑定做价格玻璃钢雕塑厂排行榜玻璃钢花盆新款玻璃钢艺术摆件景观雕塑制作商场周年美陈创意视频河北佛像玻璃钢雕塑定做价格制作玻璃钢雕塑产品报价沈阳公园玻璃钢雕塑厂家玻璃钢花盆怎么做湘潭玻璃钢大白菜雕塑郑州铸铜玻璃钢仿铜雕塑宛城玻璃钢雕塑定制甘南广场玻璃钢雕塑定制赤水玻璃钢雕塑厂山东秋季商场美陈多少钱台州个性化玻璃钢雕塑设计武汉环保玻璃钢雕塑订做价格文山景观玻璃钢雕塑设计户外玻璃钢雕塑费用是多少商场美陈3d模型河北玻璃钢雕塑供货商贵州创意玻璃钢雕塑定制保定仿铜玻璃钢雕塑公司商场简单美陈图片长沙商场美陈雕塑价格昆山圣诞商场美陈商场美陈定制道具临汾玻璃钢花盆新乡玻璃钢雕塑设计革命主题玻璃钢人物雕塑参考价香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警汪小菲曝离婚始末遭遇山火的松茸之乡雅江山火三名扑火人员牺牲系谣言何赛飞追着代拍打萧美琴窜访捷克 外交部回应卫健委通报少年有偿捐血浆16次猝死手机成瘾是影响睡眠质量重要因素高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了小米汽车超级工厂正式揭幕中国拥有亿元资产的家庭达13.3万户周杰伦一审败诉网易男孩8年未见母亲被告知被遗忘许家印被限制高消费饲养员用铁锨驱打大熊猫被辞退男子被猫抓伤后确诊“猫抓病”特朗普无法缴纳4.54亿美元罚金倪萍分享减重40斤方法联合利华开始重组张家界的山上“长”满了韩国人?张立群任西安交通大学校长杨倩无缘巴黎奥运“重生之我在北大当嫡校长”黑马情侣提车了专访95后高颜值猪保姆考生莫言也上北大硕士复试名单了网友洛杉矶偶遇贾玲专家建议不必谈骨泥色变沉迷短剧的人就像掉进了杀猪盘奥巴马现身唐宁街 黑色着装引猜测七年后宇文玥被薅头发捞上岸事业单位女子向同事水杯投不明物质凯特王妃现身!外出购物视频曝光河南驻马店通报西平中学跳楼事件王树国卸任西安交大校长 师生送别恒大被罚41.75亿到底怎么缴男子被流浪猫绊倒 投喂者赔24万房客欠租失踪 房东直发愁西双版纳热带植物园回应蜉蝣大爆发钱人豪晒法院裁定实锤抄袭外国人感慨凌晨的中国很安全胖东来员工每周单休无小长假白宫:哈马斯三号人物被杀测试车高速逃费 小米:已补缴老人退休金被冒领16年 金额超20万

玻璃钢生产厂家 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化