springboot集成swagger的pom依赖

pom依赖加入以下内容

//版本一致做个属性
	<properties>
        <swagger.version>2.6.1</swagger.version>
    </properties>
    
		<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

Swagger配置类SwaggerConfig内容

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@ComponentScan(basePackages = "com.example.demo.controller")//配置扫描的基础包
public class SwaggerConfig {

    @Bean //作为bean纳入spring容器
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .paths(PathSelectors.any())
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .build();
    }
    private ApiInfo apiInfo(){
        return  new ApiInfoBuilder()
                .title("API接口文档")
                .description("API接口文档,及相关接口的说明")
                .version("1.0.0")
                .build();
    }

}

在每个方法上添加@ApiOperation,如下

@RestController
@RequestMapping("/api/v1/user")
@EnableSwagger2
@Api
public class UserController {
    @Autowired
    private UserService userService;

    BindingResult bindingResult;

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public Result login(@RequestBody @Valid User user, BindingResult errors){

        List<FieldError> fieldErrors = errors.getFieldErrors();
        if(!fieldErrors.isEmpty()){
            System.out.println(fieldErrors.get(0).getDefaultMessage());
            return Result.resultError(fieldErrors.get(0).getDefaultMessage(),100);
        }
        return userService.login(user.getUsername(), user.getPassword());
    }

}

运行Application,访问地址http://localhost:port/swagger-ui.html即可

界面风格如下
springboot集成swagger的pom依赖
可更换版本号界面风格会发生变化,前段时间看到一个比较好用的版风格如下
springboot集成swagger的pom依赖

如需要用此则只需更换springfox-swagger-ui为

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

注意这个的版本访问地址使用http://localhost:port/doc.html#

上一篇:swagger工具的使用


下一篇:【Swagger】-SpringBoot中集成Swagger使用