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即可
界面風格如下
可更換版本號界面風格會發生變化,前段時間看到一個比較好用的版風格如下
如需要用此則只需更換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#