SpringBoot接入Swagger及Swagger-bootstrap-ui

x33g5p2x  于10个月前 转载在 Bootstrap  
字(5.9k)|赞(0)|评价(0)|浏览(73)

Demo地址:https://gitee.com/pengld-demo/swagger-demo/

Maven依赖

<!--Swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    <exclusions>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>1.5.21</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.21</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

Swagger配置

package cn.pengld.swagger.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;

/** * 项目名称:apidoc * 设置 dev test 环境开启 prod 环境就关闭了 */
@EnableWebMvc
@EnableSwagger2
@Configuration
//@Profile({"local", "dev", "fat", "uat", "prefive", "pre"})
public class SwaggerConfig extends WebMvcConfigurationSupport {
    @Value("${swagger.path}")
    private String swaggerPath;

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public Docket createRestApi() {
        //在配置好的配置类中增加此段代码即可
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<Parameter>();

        //name表示名称,description表示描述
        //required表示是否必填,defaultvalue表示默认值
        ticketPar.name("ticket").description("ticket")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();

        parameters.add(ticketPar.build());

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(basePackage(swaggerPath))
                .paths(PathSelectors.any()).build().globalOperationParameters(parameters);
    }

    /** * api文档的详细信息函数,注意这里的注解引用的是哪个 * * @return */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(!StringUtils.isEmpty(applicationName)?applicationName.toUpperCase() +"服务-API接口":"API接口")
                .version("1.0")
                .description("API-描述")
                .build();
    }

    
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(",")) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
package cn.pengld.swagger.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer  {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

controller配置

package cn.pengld.swagger.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(value = "/user", tags = "用户相关接口")
public class UserController {

    @ApiOperation(value = "/getUserList", notes = "获取用户列表", httpMethod = "GET")
    @GetMapping(value = "/getUserList")
    public List<User> getUserList(){
        List<User> userList = new ArrayList();
        userList.add(new User(1L,"Jack"));
        return userList;
    }
}

@Data
@AllArgsConstructor
class User{
    @ApiModelProperty(value = "id", name = "id")
    Long id;

    @ApiModelProperty(value = "name", name = "name")
    String name;
}

新版本的Swagger-bootstrap-ui 已改名为 knif4j

相关文章

热门文章

更多