JAVA入门[23]-SpringBoot配置Swagger2

一、新建SpringBoot站点
1.新建module,然后引入pom依赖:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.新建Controller文件

@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping(value = "/index",method= RequestMethod.GET)
public String index(@RequestParam(value="name", required=false, defaultValue="World") String name) {
return "demo "+name;
}
}

3.新建SpringBoot启动文件

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ContentPlatformWebapiApplication {
public static void main(String[] args) {
SpringApplication.run(ContentPlatformWebapiApplication.class,args);
}
}

4.运行,http://localhost:8080/demo/index?name=aa

二、配置Swagger2
1.引入Swagger pom依赖项

<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>

2.添加Swagger2 java配置文件

@Configuration
@EnableSwagger2
public class Swagger2Config { @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage(“com.cathy.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试接口平台API")
.description(“cathy demo API.")
.termsOfServiceUrl("Terms of service")
.contact("myeaddress@company.com")
.version("1.0")
.build();
} }

3.为controller添加swagger注解

@RestController
@RequestMapping("/demo")
@Api(value = "API - DemoController", description = "demo接口")
public class DemoController { @RequestMapping(value = "/index", method = RequestMethod.GET)
@ApiOperation(value = "首页", notes = "demo index")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "name", required = false,
dataType = "string", paramType = "query", defaultValue = "World")
})
public String index(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
return "demo " + name;
}
}

4.运行:http://localhost:8080/swagger-ui.html

上一篇:python基础知识4——collection类——计数器,有序字典,默认字典,可命名元组,双向队列


下一篇:float/double 浮点数据*100精度丢失问题