Spring3与swagger2结合
1.引入jar包
<swagger.version>1.5.8</swagger.version>
<io.springfox.version>2.5.0</io.springfox.version>
<!-- swagger start -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${io.springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${io.springfox.version}</version>
</dependency>
<!-- swagger end -->
2.配置文件
/*** Created by max on 8/16/16.
*
*/
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket getApiInfo() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("outer api")
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(outApiInfo());
}
private ApiInfo outApiInfo() {
return new ApiInfo(
"mylearn 前后端接口-外部", // title 标题
"APi接口文档", // description 描述 标题下
"1.0.0", // version
"http://mylearn/*", // termsOfService
new Contact("xieyuebin","","xieyuebin@meituan.com"), // contact
"Apache 2.0", // licence
"http://www.apache.org/licenses/LICENSE-2.0.html" // licence url
);
}
@Bean
public UiConfiguration getUiConfig() {
return new UiConfiguration(
null,// url,暂不用
"none", // docExpansion => none | list
"alpha", // apiSorter => alpha
"schema", // defaultModelRendering => schema
UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
false, // enableJsonEditor => true | false
true); // showRequestHeaders => true | false
}
3.配置静态资源;
<!-- swagger ui 的静态资源交由default处理--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/swagger-ui.html</url-pattern> </servlet-mapping>
4.接口实现
* Created by max on 8/16/16.
*/
@Controller
@RequestMapping(value = "/test", consumes = "application/json", produces = "application/json")
public class TestController {
private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
@ApiOperation(value = "swagger test", notes = "swagger test first", tags = {SwaggerConstants.TEST_TAG})
@ResponseBody
@RequestMapping(value = "/first", method = RequestMethod.POST)
public OutResult<String> first(@RequestBody UserForm userForm) {
LOGGER.info("first userForm={}", userForm);
throw new RuntimeException("dd");
/*
return OutResult.successResult(userForm.getUsername());
*/
}
然后我们启动项目,然后通过url:localhost:8080/swagger-ui.html来访问,就可以看到swagger文档界面了
5.注意
注意在配置过滤器时,swagger2和servlet好像有冲突,所以在2.配置文件 使用@EnableSwagger2来进行Bean方式配置