Sonar Swagger插件
插件地址: swagger-plugin
本文使用的swagger框架为Springdoc
插件编写思路
- 判断@RestController的类是否带有swagger注解
- 判断类中@RequestMapping的方法是否带有swagger注解
- 判断方法参数是否带有swagger注解
- DTO,Enum等处理
TreeVisitor 说明
可以继承TreeVisitor扫描类中指定的代码
开发步骤
找到@RestController的注解
提示添加@Tag注解
@Override
public void visitClass(ClassTree tree) {
Symbol.TypeSymbol symbol = tree.symbol();
boolean isController = isController(symbol.metadata());
if (isController) {
context.reportIssue(this, tree, "请确认是否可以使用@RestController注解");
} else {
boolean isRestController = isRestController(symbol.metadata());
boolean hasTag = hasTag(symbol.metadata());
if (isRestController && !hasTag) {
context.reportIssue(this, tree, "需要添加@Tag注解");
}
}
super.visitClass(tree);
}
判断RequestMapping注解方法使用添加文档注解并判断参数是否添加@Schema
@Override
public void visitMethod(MethodTree tree) {
Symbol.MethodSymbol methodSymbol = tree.symbol();
boolean isRestController = isRestController(methodSymbol.owner().metadata());
boolean isMapping = isMapping(methodSymbol.metadata());
if (isRestController && isMapping) {
if (!hasOperation(methodSymbol.metadata())) {
context.reportIssue(this, tree, "需要添加@Operation注解");
}
for (VariableTree param : tree.parameters()) {
TypeTree typeOfParam = param.type();
// isArray
boolean isArray = typeOfParam.symbolType().isArray();
if (isArray) {
arrayIssue((ArrayTypeTree) typeOfParam);
} else {
if (!collectionIssue(typeOfParam)) {
if (!mapIssue(typeOfParam)) {
if (!objectIssue(typeOfParam)) {
systemIssue(typeOfParam);
}
}
}
}
}
}
super.visitMethod(tree);
}
判断参数中成员是否添加@Schema
@Override
public void visitVariable(VariableTree tree) {
Symbol ownerSymbol = tree.symbol().owner();
if (ownerSymbol instanceof Symbol.TypeSymbol) {
boolean hasSchema = hasSchema(ownerSymbol.metadata());
if (hasSchema) {
Symbol symbol = tree.symbol();
boolean fieldHasSchema = hasSchema(symbol.metadata());
boolean hasHidden = hasHidden(symbol.metadata());
if (!fieldHasSchema && !hasHidden && (!(symbol.isFinal() || symbol.isStatic()))) {
context.reportIssue(this, tree, "需要添加@Schema注解");
}
}
}
super.visitVariable(tree);
}