1.直接干货
引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
创建swagger配置类
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = {"com.booway.pm.facade.controller"})
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.booway.pm.facade.controller"))
.paths(PathSelectors.any()).build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
Contact contact = new Contact("lisboy", "http://lisboy.top", "lisboy98@163.com");
return new ApiInfoBuilder()
.title("xxx系统")
.description("xxx管理")
.contact(contact)
.version("1.0.0")
.build();
}
}
写入springMVC.xml
<bean class="com.booway.pm.facade.config.SwaggerConfig"/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
测试代码
@RestController
@Api(tags = "登录/登出/token验证")
public class LoginController
{
@Autowired
private HttpService httpService;
@ApiOperation(value="登录", httpMethod="POST",response=Result.class)
@PostMapping("login")
public BwResult<Object> login(String username, String password) throws DocumentException
{
httpService.login(username, password);
return Result.success("登录成功", CommonUtils.getThreadLocal().getToken());
}
}
测试成功界面
访问连接:http://localhost:8080/项目名/swagger-ui.html
http://localhost:8080/项目名/v2/api-docs
2.遇到的坑
当你使用fastjson时有可能会碰见swagger界面是这样的
然后打开文档界面是空白的{}这个字符
其原因是使用了fastjson替换了原本的springmvc的默认 json解析方式
解决办法就是去掉这段代码即可,后续如果遇到其他坑,我再补充说明