import io.swagger.annotations.ApiOperation;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import springfox.documentation.RequestHandler;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spi.service.contexts.RequestMappingContext;
import java.lang.reflect.Field;
@Component
@Order
public class CustomOperationBuilderPlugin implements OperationBuilderPlugin {
private static Field cxt = null;
private static Field hd = null;
static {
cxt = ReflectionUtils.findField( OperationContext.class, "requestContext");
hd = ReflectionUtils.findField( RequestMappingContext.class, "handler");
assert cxt != null;
assert hd != null;
cxt.setAccessible( true );
hd.setAccessible( true );
}
@Override
public void apply(OperationContext context) {
try {
RequestMappingContext requestMappingContext = (RequestMappingContext) cxt.get( context);
RequestHandler requestHandler =(RequestHandler) hd.get(requestMappingContext);
// 获取@ApiOperation注解
ApiOperation apiOperation = requestHandler.getHandlerMethod().getMethodAnnotation(ApiOperation.class);
if (apiOperation != null) {
// 动态修改value值
String newValue = "动态修改后的描述";
context.operationBuilder().summary( apiOperation.value() + newValue);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
;
}
@Override
public boolean supports(DocumentationType documentationType) {
return DocumentationType.SWAGGER_2.equals(documentationType);
}
}
05-11
1万+
05-20
2015
04-05
1463