SpringBoot扫描注册注解

有个小需求是扫描在SpringBoot 注册的RequestMapping接口地址,可以先扫描所有使用Controller注解的类,然后获取他们的方法,判断使用的RequestMapping注解,再获取value,就能拿到接口地址了。下面为代码片段

    /**
     * 扫描使用注解的类
     * @param packageName 扫描包名
     * @param annotation 注解类
     * @return 扫描到的集合
     */
    public static List<class> scanClass(String packageName, Class annotation) {
        List<class> classList = new ArrayList&lt;>();
        if (ObjectUtils.isEmpty(packageName)) {
            return classList;
        }
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        TypeFilter includeFilter = (metadataReader, metadataReaderFactory) -> true;
        provider.addIncludeFilter(includeFilter);
        Set<beandefinition> beanDefinitionSet = new HashSet&lt;>();
        // 指定扫描的包名
        Set<beandefinition> candidateComponents = provider.findCandidateComponents(packageName);
        beanDefinitionSet.addAll(candidateComponents);

        beanDefinitionSet.forEach(beanDefinition -> {
            try {
                Class clazz = Class.forName(beanDefinition.getBeanClassName());

                if (!ObjectUtils.isEmpty(annotation)) {
                    if (!ObjectUtils.isEmpty(AnnotationUtils.getAnnotation(clazz, annotation))) {
                        classList.add(clazz);
                    }
                } else {
                    classList.add(clazz);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
//            System.out.println(definition.getBeanClassName());
        });
        return classList;
    }

    /**
     * 获取Url
     * @param packageName 扫描包名
     * @param className 指定类,如无指定类,为null即可
     * @return url集合
     */
    public static List<string> getUrls(String packageName,String className){
        List<class> list= scanClass(packageName, Controller.class);
        List<string> urls=new ArrayList&lt;>();
        for (Class aClass : list) {
            if(className!=null&amp;&amp;!aClass.getSimpleName().equals(className)){
                continue;
            }
            Method[] methods= aClass.getDeclaredMethods();
            for (Method method : methods) {
                RequestMapping ls=method.getAnnotation(RequestMapping.class);
                if(ls!=null) {
                    urls.add(ls.value()[0]);
                }
            }
        }
        return urls;
    }

发表评论

您的电子邮箱地址不会被公开。