因为项目长时间积累接口比较多,需要删除不用接口,这里通过工具类递归遍历目录获取calss进行反射创建,获取接口方法以及相关SpringMvc注解,并进行解析。其他方式有很多,目前需求这个就可满足。
直接放入代码
package cn.crl.report;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* 类工具
*/
public class ClassUtils {
private static final String removeStr = "src.main.java.";
private static final String commonPath = "\\src\\main\\java";
private URL projectPath;
private URLClassLoader classLoader;
private String projectPathStr;
/**
* 映射器注解
*/
private static final List<Class> mapperAnnotationLs = new ArrayList() {{
add(RequestMapping.class);
add(PostMapping.class);
add(GetMapping.class);
add(PutMapping.class);
add(DeleteMapping.class);
add(PatchMapping.class);
}};
public static void main(String[] args) throws Exception {
ClassUtils classUtils = new ClassUtils("E:\\xmdome\\crl-report-form\\crl-report-form-api");
List<InterfaceDo> arrayList = new ArrayList<>();
classUtils.getAllIntefaces(classUtils.projectPathStr, null, arrayList);
arrayList.forEach(System.out::println);
}
public ClassUtils(String filePath) {
init(filePath);
}
//初始化
private void init(String filePath) {
try {
this.projectPathStr = filePath + commonPath;
File file = new File(projectPathStr);
if (file == null || !file.exists()) {
//创建下
throw new RuntimeException("当前目录不存在");
}
projectPath = file.toURI().toURL();
//加载文件
classLoader = new URLClassLoader(new URL[] {projectPath});
} catch (Exception e) {
System.out.println("文件不存在" + e);
}
}
/**
* @param filePath
* @param packageName
* @return
* @throws Exception
*/
public void getAllIntefaces(String filePath, String packageName, List<InterfaceDo> urlList) throws Exception {
Assert.notNull(urlList, "不可为空");
File dir = new File(filePath);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
String fileName = file.getName();
System.out.println("开始扫描文件:" + fileName + ",包名:" + packageName);
if (fileName.endsWith(".java")) {
String className = null;
if (packageName != null) {
className = packageName + '.' + fileName.substring(0, fileName.length() - 5);
} else {
className = fileName.substring(0, fileName.length() - 5);
}
className = className.replaceAll(removeStr, "").trim();
//加载类
Class<?> aClass = null;
try {
aClass = classLoader.loadClass(className);
} catch (Error e) {
System.out.println(e);
continue;
} catch (Exception e) {
System.out.println(e);
continue;
}
//判断下controller 接口是否有注解 @Controller @restController
if (aClass.getAnnotation(org.springframework.stereotype.Controller.class) == null
&& aClass.getAnnotation(org.springframework.web.bind.annotation.RestController.class) == null) {
continue;
}
//判断下是否存在接口@RequestMapper注解
if (!containMapperAnnotationLsByClass(aClass)) {
continue;
}
//获取所有public方法
Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (Modifier.isPublic(method.getModifiers()) && containMapperAnnotationLsByMonth(method)) {
//获取类上url
String url1[] = getMappingPathUrlByClass(aClass);
//获取方法url
String url2 = getMappingPathUrlByMonth(method);
//格式化
if (!"/".equals(url2.substring(0, 1))) {
url2 = "/" + url2;
}
RequestMethod requestMethod = getRequestMethodByMonth(method);
if (url1 != null && url1.length > 0) {
for (String url : url1) {
//第一个是否以/开头
if (!"/".equals(url.substring(0, 1))) {
url = "/" + url;
}
InterfaceDo interfaceDo = new InterfaceDo();
interfaceDo.setUrl(url + url2);
interfaceDo.setRequestMethod(requestMethod);
urlList.add(interfaceDo);
}
} else {
InterfaceDo interfaceDo = new InterfaceDo();
interfaceDo.setUrl(url2);
interfaceDo.setRequestMethod(requestMethod);
urlList.add(interfaceDo);
}
}
}
} else if (file.isDirectory()) {
String subPackageName = null;
if (packageName != null) {
subPackageName = packageName + '.' + fileName;
} else {
subPackageName = fileName;
}
getAllIntefaces(file.getPath(), subPackageName, urlList);
}
}
}
}
/**
* 获取类上url
* 类上可指定多个url
*/
private String[] getMappingPathUrlByClass(Class clazz) {
String[] value = null;
for (Class aClass : mapperAnnotationLs) {
Annotation annotation = clazz.getAnnotation(aClass);
if (annotation != null) {
value = getAnnotationValue(annotation);
}
}
return value;
}
/**
* 获取方法上url
*/
private String getMappingPathUrlByMonth(Method clazz) {
String[] value = null;
for (Class aClass : mapperAnnotationLs) {
Annotation annotation = clazz.getAnnotation(aClass);
value = getAnnotationValue(annotation);
}
return Optional.ofNullable(value).filter(k -> k.length > 0).map(k -> k[0]).orElse("");
}
/**
* 获取注解中存在接口注解的value
* @param annotation
* @return
*/
private String[] getAnnotationValue(Annotation annotation) {
String[] value = null;
if (annotation != null) {
if (annotation instanceof RequestMapping) {
value = ((RequestMapping)annotation).value();
} else if (annotation instanceof PostMapping) {
value = ((PostMapping)annotation).value();
} else if (annotation instanceof GetMapping) {
value = ((GetMapping)annotation).value();
} else if (annotation instanceof PutMapping) {
value = ((PutMapping)annotation).value();
} else if (annotation instanceof DeleteMapping) {
value = ((DeleteMapping)annotation).value();
} else if (annotation instanceof PatchMapping) {
value = ((PatchMapping)annotation).value();
}
}
return value;
}
/**
* 获取ApiOperation方法级别的注解
* @param method
* @return
*/
private String getApiOperationByMethod(Method method) {
return null;
}
/**
* 获取方法级别的注解
* @param clazz
* @return
*/
private RequestMethod getRequestMethodByMonth(Method clazz) {
RequestMethod method = null;
for (Class aClass : mapperAnnotationLs) {
Annotation annotation = clazz.getAnnotation(aClass);
if (annotation != null) {
if (annotation instanceof RequestMapping) {
//空
} else if (annotation instanceof PostMapping) {
method = RequestMethod.POST;
} else if (annotation instanceof GetMapping) {
method = RequestMethod.GET;
} else if (annotation instanceof PutMapping) {
method = RequestMethod.PUT;
} else if (annotation instanceof DeleteMapping) {
method = RequestMethod.DELETE;
} else if (annotation instanceof PatchMapping) {
method = RequestMethod.PATCH;
}
}
}
return method;
}
/**
* 判断方法是否包含注解
*/
private boolean containMapperAnnotationLsByMonth(Method method) {
for (Class aClass : mapperAnnotationLs) {
if (method.getAnnotation(aClass) != null) {
return true;
}
}
return false;
}
/**
* 判断类是否包含注解
*/
private boolean containMapperAnnotationLsByClass(Class clazz) {
for (Class aClass : mapperAnnotationLs) {
if (clazz.getAnnotation(aClass) != null) {
return true;
}
}
return false;
}
/**
* 接口信息对象
*/
class InterfaceDo {
/**
* 描述
*/
private String name;
/**
* url
*/
private String url;
/**
* 请求类型
*/
private RequestMethod requestMethod;
public InterfaceDo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public RequestMethod getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(RequestMethod requestMethod) {
this.requestMethod = requestMethod;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("InterfaceDo{");
sb.append("name='").append(name).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", requestMethod=").append(requestMethod);
sb.append('}');
return sb.toString();
}
}
}
我们只需要传入一个filePath,也就是你所涉及接口主目录。
目前工具类需要放入项目包里面,与你要导出项目在一个环境即可。
其他方式也有很多。这里先介绍这种