下面列出了怎么用io.swagger.annotations.Api的API类实例代码及写法,或者点击链接到github查看源代码。
@Bean
public Docket createRestApi(ApplicationContext context,
MicaSwaggerProperties properties) {
// 组名为应用名
String appName = context.getId();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.globalOperationParameters(globalHeaders(properties))
.apiInfo(apiInfo(appName, properties)).select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
// 如果开启认证
if (properties.getAuthorization().getEnabled()) {
docket.securitySchemes(Collections.singletonList(apiKey(properties)));
docket.securityContexts(Collections.singletonList(securityContext(properties)));
}
return docket;
}
private Predicate<RequestHandler> getControllerPredicate() {
groupName = groupList.get(groupIndex);
List<String> apiTags = groupMap.get(groupName);
Predicate<RequestHandler> methodPredicate = (input) -> {
Api api = null;
Optional<Api> apiOptional = input.findControllerAnnotation(Api.class);
if (apiOptional.isPresent()) {
api = apiOptional.get();
}
List<String> tags = Arrays.asList(api.tags());
if (api != null && apiTags.containsAll(tags)) {
return true;
}
return false;
};
groupIndex++;
return Predicates.and(RequestHandlerSelectors.withClassAnnotation(RestController.class), methodPredicate);
}
private static void annotateApiAnn(ApiInfo info, AnnotationsAttribute attr, ConstPool constPool) {
Annotation apiAnn = attr.getAnnotation(Api.class.getTypeName());
MemberValue value;
if (isNull(apiAnn)) {
apiAnn = new Annotation(Api.class.getName(), constPool);
}
if (isNull(value = apiAnn.getMemberValue(ApiInfo.HIDDEN)) || !((BooleanMemberValue) value).getValue()) {
apiAnn.addMemberValue(ApiInfo.HIDDEN, new BooleanMemberValue(info.hidden(), constPool));
}
ArrayMemberValue arrayMemberValue = (ArrayMemberValue) apiAnn.getMemberValue(TAGS);
if (isNull(arrayMemberValue)) {
arrayMemberValue = new ArrayMemberValue(constPool);
arrayMemberValue.setValue(new MemberValue[1]);
}
StringMemberValue tagMemberValue = (StringMemberValue) arrayMemberValue.getValue()[0];
if (isNull(tagMemberValue) || StringUtils.isEmpty(tagMemberValue.getValue())) {
tagMemberValue = new StringMemberValue(info.tag(), constPool);
}
tagMemberValue.setValue(info.tag());
arrayMemberValue.getValue()[0] = tagMemberValue;
apiAnn.addMemberValue(TAGS, arrayMemberValue);
attr.addAnnotation(apiAnn);
}
@Bean
public Docket createRestApi() {
// 获取需要扫描的包
String[] basePackages = getBasePackages();
ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select();
// 如果扫描的包为空,则默认扫描类上有@Api注解的类
if (ArrayUtils.isEmpty(basePackages)) {
apiSelectorBuilder.apis(RequestHandlerSelectors.withClassAnnotation(Api.class));
} else {
// 扫描指定的包
apiSelectorBuilder.apis(basePackage(basePackages));
}
Docket docket = apiSelectorBuilder.paths(PathSelectors.any())
.build()
.enable(swaggerProperties.isEnable())
.ignoredParameterTypes(ignoredParameterTypes)
.globalOperationParameters(getParameters());
return docket;
}
protected Class<?> getSubResource(Method method) {
final Class<?> rawType = method.getReturnType();
final Class<?> type;
if (Class.class.equals(rawType)) {
type = getClassArgument(method.getGenericReturnType());
if (type == null) {
return null;
}
} else {
type = rawType;
}
if (type.getAnnotation(Api.class) != null) {
return type;
}
// For sub-resources that are not annotated with @Api, look for any HttpMethods.
for (Method m : type.getMethods()) {
if (extractOperationMethod(null, m, null) != null) {
return type;
}
}
return null;
}
protected Set<String> extractTags(Api api) {
Set<String> output = new LinkedHashSet<String>();
boolean hasExplicitTags = false;
for (String tag : api.tags()) {
if (!"".equals(tag)) {
hasExplicitTags = true;
output.add(tag);
}
}
if (!hasExplicitTags) {
// derive tag from api path + description
String tagString = api.value().replace("/", "");
if (!"".equals(tagString)) {
output.add(tagString);
}
}
return output;
}
@Override
public void applyConsumes(ReaderContext context, Operation operation, Method method) {
final List<String> consumes = new ArrayList<String>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
if (apiOperation != null) {
consumes.addAll(parseStringValues(apiOperation.consumes()));
}
if (consumes.isEmpty()) {
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiAnnotation != null) {
consumes.addAll(parseStringValues(apiAnnotation.consumes()));
}
consumes.addAll(context.getParentConsumes());
}
for (String consume : consumes) {
operation.consumes(consume);
}
}
@Override
public void applyProduces(ReaderContext context, Operation operation, Method method) {
final List<String> produces = new ArrayList<String>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
if (apiOperation != null) {
produces.addAll(parseStringValues(apiOperation.produces()));
}
if (produces.isEmpty()) {
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiAnnotation != null) {
produces.addAll(parseStringValues(apiAnnotation.produces()));
}
produces.addAll(context.getParentProduces());
}
for (String produce : produces) {
operation.produces(produce);
}
}
@Override
public void applySchemes(ReaderContext context, Operation operation, Method method) {
final List<Scheme> schemes = new ArrayList<Scheme>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiOperation != null) {
schemes.addAll(parseSchemes(apiOperation.protocols()));
}
if (schemes.isEmpty() && apiAnnotation != null) {
schemes.addAll(parseSchemes(apiAnnotation.protocols()));
}
for (Scheme scheme : schemes) {
operation.scheme(scheme);
}
}
@Override
public void applyConsumes(ReaderContext context, Operation operation, Method method) {
final List<String> consumes = new ArrayList<String>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
if (apiOperation != null) {
consumes.addAll(parseStringValues(apiOperation.consumes()));
}
if (consumes.isEmpty()) {
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiAnnotation != null) {
consumes.addAll(parseStringValues(apiAnnotation.consumes()));
}
consumes.addAll(context.getParentConsumes());
}
for (String consume : consumes) {
operation.consumes(consume);
}
}
@Override
public void applyProduces(ReaderContext context, Operation operation, Method method) {
final List<String> produces = new ArrayList<String>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
if (apiOperation != null) {
produces.addAll(parseStringValues(apiOperation.produces()));
}
if (produces.isEmpty()) {
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiAnnotation != null) {
produces.addAll(parseStringValues(apiAnnotation.produces()));
}
produces.addAll(context.getParentProduces());
}
for (String produce : produces) {
operation.produces(produce);
}
}
@Override
public void applySchemes(ReaderContext context, Operation operation, Method method) {
final List<Scheme> schemes = new ArrayList<Scheme>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiOperation != null) {
schemes.addAll(parseSchemes(apiOperation.protocols()));
}
if (schemes.isEmpty() && apiAnnotation != null) {
schemes.addAll(parseSchemes(apiAnnotation.protocols()));
}
for (Scheme scheme : schemes) {
operation.scheme(scheme);
}
}
@Override
public void process(final CtInterface<?> restServiceInterface) {
final CtAnnotation<Annotation> annotation = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(Api.class));
final String classFqn = restServiceInterface.getQualifiedName();
final RestService restService = context.getServiceDocumentation().get(classFqn);
if (restService != null) {
annotation.addValue("tags", restService.getTags());
restServiceInterface.addAnnotation(annotation);
// Add path annotation if missing
final Path pathAnnotation = restServiceInterface.getAnnotation(Path.class);
if (pathAnnotation == null) {
final CtAnnotation<Path> path = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(Path.class));
path.addValue("value", restService.getPath());
restServiceInterface.addAnnotation(path);
}
log.debug("Added @Api to {} [{}]", restServiceInterface.getQualifiedName(), classFqn);
} else {
log.error("No documentation found for {} [{}]", restServiceInterface.getQualifiedName(), classFqn);
}
}
@Override
public void process(final CtInterface<?> resourceInterface) {
final CtAnnotation<Annotation> annotation = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(Api.class));
final RestService restService = context.getServiceDocumentation().get(resourceInterface.getQualifiedName());
if (restService != null) {
String[] tags;
if (restService.getTags().contains(",")) {
tags = restService.getTags().split(",");
} else {
tags = new String[]{ restService.getTags() };
}
annotation
// .addValue("tags", tags)
.addValue("hidden", true);
resourceInterface.addAnnotation(annotation);
} else {
log.error("No documentation for resource {} found.", resourceInterface.getQualifiedName());
}
}
protected Class<?> getSubResource(Method method) {
final Class<?> rawType = method.getReturnType();
final Class<?> type;
if (Class.class.equals(rawType)) {
type = getClassArgument(method.getGenericReturnType());
if (type == null) {
return null;
}
} else {
type = rawType;
}
if (type.getAnnotation(Api.class) != null) {
return type;
}
// For sub-resources that are not annotated with @Api, look for any HttpMethods.
for (Method m : type.getMethods()) {
if (extractOperationMethod(null, m, null) != null) {
return type;
}
}
return null;
}
protected Set<String> extractTags(Api api) {
Set<String> output = new LinkedHashSet<>();
boolean hasExplicitTags = false;
for (String tag : api.tags()) {
if (!"".equals(tag)) {
hasExplicitTags = true;
output.add(tag);
}
}
if (!hasExplicitTags) {
// derive tag from api path + description
String tagString = api.value().replace("/", "");
if (!"".equals(tagString)) {
output.add(tagString);
}
}
return output;
}
@Test
public void testNamespacingByAnnotation() {
final Settings settings = TestUtils.settings();
settings.outputFileType = TypeScriptFileType.implementationFile;
settings.generateJaxrsApplicationInterface = true;
settings.generateJaxrsApplicationClient = true;
settings.restNamespacing = RestNamespacing.byAnnotation;
settings.restNamespacingAnnotation = Api.class;
final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(OrganizationApplication.class));
final String errorMessage = "Unexpected output: " + output;
Assert.assertTrue(errorMessage, output.contains("class OrgApiClient implements OrgApi "));
Assert.assertTrue(errorMessage, output.contains("class OrganizationApplicationClient implements OrganizationApplication "));
Assert.assertTrue(errorMessage, !output.contains("class OrganizationsResourceClient"));
Assert.assertTrue(errorMessage, !output.contains("class OrganizationResourceClient"));
Assert.assertTrue(errorMessage, !output.contains("class PersonResourceClient"));
}
/**
* swagger API
*
* @param joinPoint
* @return
* @throws Exception
*/
private Api getApi(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Api classAnnotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), Api.class);
if (method != null) {
return classAnnotation;
}
return null;
}
@Override
public List<RequestHandler> requestHandlers() {
return byPatternsCondition().sortedCopy(nullToEmptyList(serviceBeans).stream()
.filter(bean -> AnnotatedElementUtils.hasAnnotation(bean.getInterfaceClass(), Api.class))
.reduce(newArrayList(), toMappingEntries(), (o1, o2) -> o1)
.stream().map(toRequestHandler()).collect(Collectors.toList()));
}
private void readApi() {
Api api = findAnnotation(Api.class);
if (nonNull(api)) {
hidden |= api.hidden();
for (String tag : api.tags()) {
if (!StringUtils.isEmpty(tag)) {
this.tag = tag;
}
}
}
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(Collections.singletonList(securityScheme()));
}
/**
* 创建一个 Docket 组件 把自定义的 appInfo 装载到里面
* */
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//指定 apiInfo初始化信息
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//只有 @api 的可以被识别为 swagger 文档
.paths(PathSelectors.any())//指定路径
.build();
}
@ApiOperation("AnnotationUtil使用:注解工具类")
@GetMapping("/annotationUtil")
public CommonResult annotationUtil() {
//获取指定类、方法、字段、构造器上的注解列表
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
//获取指定类型注解
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:{}", api.description());
//获取指定类型注解的值
Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);
LOGGER.info("annotationUtil annotationValue:{}", annotationValue);
return CommonResult.success(null, "操作成功");
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("online.iizvv.controls"))
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
/**
* Every Docket bean is picked up by the swagger-mvc framework - allowing for multiple
* swagger groups i.e. same code base multiple swagger resource listings.
*/
@Bean
public Docket customDocket() {
// return new Docket(DocumentationType.SWAGGER_2);
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build().enable(Configration.enableSwagger);//<--- Flag to enable or disable possibly loaded using a property file
}
private static <M extends IMenu<M>> void scanControllerMenus(Set<Class<?>> controllerClassSet, Class<M> menuClz,
List<M> allControllerMenus) throws InstantiationException, IllegalAccessException {
Set<String> controllerApiNames = new HashSet<String>();
for (Class<?> controllerClass : controllerClassSet) {
Api apiAnno = AnnotatedElementUtils.findMergedAnnotation(controllerClass, Api.class);
Menu menuAnno = AnnotatedElementUtils.findMergedAnnotation(controllerClass, Menu.class);
VisitCheck controllerVisitCheckAnno = AnnotatedElementUtils.findMergedAnnotation(controllerClass, VisitCheck.class);
final String controllerName = StringUtil.trimRight(controllerClass.getSimpleName(), CONTROLLER_SUBFIX);
String route = ControllerHelpers.getRoute(controllerClass,controllerName, false);
route = StringUtil.startWithSlash(route);
boolean isMenu = menuAnno != null && menuAnno.value();
MenuType controllerVisitType = getMenuTypeByControllerName(controllerName, isMenu);
VisitCheckType controllerVisitCheckType = VisitCheckType.getCheckType(controllerVisitCheckAnno != null);
String apiName = apiAnno != null ? apiAnno.value() : null;
if (StringUtil.isBlank(apiName)) {
apiName = StringUtil.trimLeftFormRightTo(controllerName, StringUtil.UNDERLINE);
}
AssertUtil.mustNotContainsAndAdd(controllerApiNames, apiName, "菜单名称不能相同:" + apiName);
M controllerMenu = IMenu.createMenu(menuClz, controllerName, null, null, apiName, route, controllerVisitType, controllerVisitCheckType);
allControllerMenus.add(controllerMenu);
String controllerUrl = getControllerUrl(controllerClass);
scanMethodMenus(menuClz, controllerClass, controllerName, controllerMenu, controllerUrl);
}
}
public Boolean getHidden() {
if (hidden == null) {
Api apiAnno = getApiAnno();
hidden = apiAnno == null || apiAnno.hidden();
}
return hidden;
}
public String getDescription() {
Api apiAnno = AnnotationUtil.getAnnotation(getClazz(), Api.class);
if (apiAnno != null) {
String value = apiAnno.value();
if (StringUtil.isNotEmpty(value)) {
return value;
}
}
return "";
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("top.wingcloud.controller"))
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("top.wingcloud.controller"))
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}