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列表
最新推荐文章于 2024-07-14 21:25:46 发布