spring boot swagger 分组 定制 显示API

本文介绍了如何在Spring Boot项目中使用Swagger进行API文档的分组和定制显示,包括在pom.xml配置,注解的使用,以及如何设置innerAPI和openAPI的不同访问策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom.xml

   

	
		 <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>


configuration

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import com.google.common.base.Predicate;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * SwaggerConfig
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {


    /**
     * 定义api组,
     */
    @Bean
    public Docket innerApi() {
    	
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("innerApi")
                .genericModelSubstitutes(DeferredResult.class)
//                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zybros.jinlh"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(innerApiInfo());
    }

    @Bean
    public Docket openApi() {
    	
    	
    	Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
            @Override
            public boolean apply(RequestHandler input) {
//                Class<?> declaringClass = input.declaringClass();
//                if (declaringClass == BasicErrorController.class)// 排除
//                    return false;
//                if(declaringClass.isAnnotationPresent(ApiOperation.class)) // 被注解的类
//                    return true;
//                if(input.isAnnotatedWith(ResponseBody.class)) // 被注解的方法
//                    return true;
                if (input.isAnnotatedWith(ApiOperation.class))//只有添加了ApiOperation注解的method才在API中显示
                    return true;
                return false;
            }
        };
    	
    	
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("openApi")
                .genericModelSubstitutes(DeferredResult.class)
//              .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(false)
                .select()
                .apis(predicate)
                .paths(PathSelectors.any())//过滤的接口
                .build()
                .apiInfo(openApiInfo());
    }

    private ApiInfo innerApiInfo() {
        return new ApiInfoBuilder()
            .title("JinLH inner Platform API")//大标题
            .description("内部api")//详细描述
            .version("1.0")//版本
            .termsOfServiceUrl("NO terms of service")
            .contact(new Contact("stone", "https://www.jinlh.com", "787591269@qq.com"))//作者
            .license("The Apache License, Version 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
            .build();
    }

    private ApiInfo openApiInfo() {
        return new ApiInfoBuilder()
            .title("JinLH Platform API")//大标题
            .description("金老虎提供的OpenAPI")//详细描述
            .version("1.0")//版本
            .termsOfServiceUrl("NO terms of service")
            .contact(new Contact("泽佑","www.zybros.com", "787591269@qq.com"))//作者
            .license("The Apache License, Version 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
            .build();
    }
}

注解  API

@RestController
public class ProductApi extends BaseController {
		
	@ApiOperation(value="根据类别获取商品", notes="需要提供类别ID")
	@RequestMapping(value = "/wx/ctg_product_ctgs_list", method = {RequestMethod.POST,RequestMethod.GET})
	public Map<String, Object> listWithCtgs(HttpServletRequest rqs, Category ctg) throws BusinessException {
		Product p = new Product();
		if (ctg.getLevel() != null) {
			if (ctg.getLevel() == 1) {
				p.setCategoryId1(ctg.getId());
			} else if (ctg.getLevel() == 2) {
				p.setCategoryId2(ctg.getId());
			} else if (ctg.getLevel() == 3) {
				p.setCategoryId3(ctg.getId());
			}
		}
		ProductMapper mapper = this.getMybatisBaseService().getMapper(ProductMapper.class);
		p.setShopId(ctg.getShopId());
		p.setStatus(Product.Status.UP);
		List<Product> list = mapper.selectList(p);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("products", list);
		
		CategoryMapper mapper2 = this.getMybatisBaseService().getMapper(CategoryMapper.class);
		ctg.setParentId(0);
		ctg.setStatus(Category.Status.UP);
		List<Category> ctgs = mapper2.selectList(ctg);
		m.put("categories", ctgs);
		
		
		m.put("imgHttpPath", SystemConstants.PRODUCT_IMG_HTTP_PATH);
		return m;

	}

	@ApiOperation(value="获取商品信息", notes="需要提供商品ID")
	@RequestMapping(value = "/wx/product", method = {RequestMethod.POST,RequestMethod.GET})
	public Map<String, Object> get(HttpServletRequest rqs, int id) throws BusinessException {
		ProductMapper ccm = this.getMybatisBaseService().getMapper(ProductMapper.class);
		Product product = ccm.selectByPrimaryKey(id);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("product", product);
		m.put("imgHttpPath", SystemConstants.PRODUCT_IMG_HTTP_PATH);
		return m;
	}

}


swagger UI

innerAPI




openAPI



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值