package com.jianmu.config.api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
*
*/
@Slf4j
public class AnnotationTools {
private AnnotationTools() {
}
/**
* 获取被注解的接口URI列表
*
* @param scanPackage 要扫描的包路径 com.api
* @param scanClassAnnotation 类上要扫描的注解
* @param scanMethodAnnotation 方法上要扫描的注解
*/
public static List<String> findUrisByAnnoScan(String scanPackage, Class<? extends Annotation> scanClassAnnotation, Class<? extends Annotation> scanMethodAnnotation) {
//查找 ‘classpath’ 下符合要求的class文件
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
//扫描有 当前scanClassAnnotation注解的类
provider.addIncludeFilter(new AnnotationTypeFilter(scanClassAnnotation));
//指定扫描的包名
Set<BeanDefinition> candidateComponents = provider.findCandidateComponents(scanPackage);
List<String> uris = new ArrayList<>(30);
for (BeanDefinition candidateComponent : candidateComponents) {
Class<?> cls = null;
try {
cls = Class.forName(candidateComponent.getBeanClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (cls == null) {
return null;
}
RequestMapping requestMapping = cls.getAnnotation(RequestMapping.class);
String uri = null;
if (requestMapping != null) {
uri = requestMapping.value()[0];
}
//获取类中的所有的方法
Method[] methods = cls.getMethods();
for (Method method : methods) {
Annotation annotation = method.getAnnotation(scanMethodAnnotation);
GetMapping getMapping = method.getAnnotation(GetMapping.class);
PostMapping postMapping = method.getAnnotation(PostMapping.class);
if (annotation == null) {
continue;
}
if (Objects.nonNull(getMapping)) {
uri += getMapping.value()[0];
}
if (Objects.nonNull(postMapping)) {
uri += postMapping.value()[0];
}
uris.add(uri);
}
}
return uris;
}
}
获取被注解的接口uri列表
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 作者:俊俊的小熊饼干cnblogs.com/wenjunwei/p/10293490.html前言 最近在做项目权...
- python web(bottle框架)知行合一之-简单知识付费平台-”全栈“实践(11)---分页获取课程列表信...
- 上篇文章写过Python爬虫的方法,用的Scrapy框架。Python--Scrapy爬虫获取简书作者ID的全部文...