springboot读取所有自定义注解

先说下需求,是用作权限使用

自定义注解 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, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {

    String name() default "";
}

实体类 Permission

package org.com.rsmall.db.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * @ClassName Permission
 */
@Data
@Entity
@Table(name="t_permission")
@TableName(value = "t_permission")
public class Permission {

    private Long id;

    private String name;

    private  String path;

}

工具类 PermissionCollectUtils

package org.com.rsmall.wx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
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.web.bind.annotation.*;

import java.util.*;

/**
 * @ClassName PermissionCollectUtils
 */
public class PermissionCollectUtils {


    private static Logger logger = LoggerFactory.getLogger(PermissionCollectUtils.class);

    private static final String VALUE = "value";

    public static <T> List<Map<String,Object>> getAll(ResourcePatternResolver resourcePatternResolver,String classpath,Class<T> annotationClass) throws Exception {
        Resource[] resources = resourcePatternResolver.getResources(classpath);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory();
        List<Map<String, Object>> rsMap = new ArrayList<>();
        for (Resource r : resources) {
            MetadataReader reader = metaReader.getMetadataReader(r);
            resolveClass(reader, rsMap, annotationClass);
        }
        return rsMap;
    }

    private static <T> void resolveClass(MetadataReader reader, List<Map<String, Object>> maps, Class<T> annotationClass) throws Exception {
        String tagAnnotationClassCanonicalName = annotationClass.getCanonicalName();

        //获取类注解元数据
        AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
        //获取类中RequestMapping注解的属性
        Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(RequestMapping.class.getCanonicalName());
        String pathParent="";
        if (annotationAttributes != null){
            //获取类上RequestMapping注解的value
            String[] pathParents = (String[]) annotationAttributes.get(VALUE);
            if (pathParents.length>0){
                //获取类上RequestMapping注解的value
                pathParent = pathParents[0];
            }
        }

        //获取所有添加了此注解Permission的方法
        Set<MethodMetadata> annotatedMethods = annotationMetadata.getAnnotatedMethods(tagAnnotationClassCanonicalName);

        for (MethodMetadata annotatedMethod : annotatedMethods) {
            Map<String,String> rsMap=new HashMap<>();
            //获取当前方法中要扫描注解的属性
            Map<String, Object> targetAttr = annotatedMethod.getAnnotationAttributes(tagAnnotationClassCanonicalName);
            //获取方法GetMapping、PosttMapping等注解的属性
            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 has = containsPath(maps,path);
            if (has){
                logger.error("path关系映射重复");
                continue;
            }
            targetAttr.put("path",path);
            maps.add(targetAttr);
        }
    }

    private static boolean containsPath(List<Map<String, Object>> maps, String path) {
        for (Map<String, Object> map : maps) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if(entry.getValue().equals(path)){
                    return true;
                }
            }
        }
        return false;
    }

    private static 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;
    }
}
调用(下图)使用的Spring CommandLineRunner,demo是初始化存储到数据库。截图方便区分注解和实体类

​​​​


Resource[] resources = resourcePatternResolver.getResources(classpath);
也可用ApplicationContext.getResources(classpath);
但内部还是调用的ResourcePatternResolver.getResources(classpath);
ApplicationContext applicationContext = Tools.getApplicationContext();
Resource[] resources = applicationContext.getResources(classpath);
ResourcePatternResolver可注入,也可以使用以下方式。ResourceLoader
@Autowired
private ResourceLoader resourceLoader;
ResourcePatternResolver resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值