很简单的一个spring boot+Swagger2的例子

  • 用spring boot搭建一个简单的web项目(建一个maven项目依赖spring boot的项目即可),编写一个启动类。

1.spring boot依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.启动类

@SpringBootApplication

public class SwaggerApplication {

public static void main(String[] args) {

SpringApplication.run(SwaggerApplication.class, args);

}

}

  • 添加swagger依赖

<!-- swaggers2 -->

<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>

  • spring注解方式编写一个swagger的配置类

@Configuration

@EnableSwagger2

public class SwaggerConfig {

@Bean

public Docket getDocket() {

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

.select()

.apis(RequestHandlerSelectors.basePackage("com.ignitetest.test.controller"))

.paths(PathSelectors.any())

.build();

}

private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.title("Swagger測試")//標題

.description("swagger簡單測試")//説明

.contact("xxxxxxxx@163.com")//聯係

.version("1.0")//版本

.build();

}

}

 
  • 编写一个简单的接口

@RestController("/cities")

public class SwaggerController {

private Map<String,City> cities = new HashMap<>();

@ApiOperation(value="新增一个城市",notes="根据提交的信息新增一个城市")

@ApiImplicitParam(name="city",value="要增加的城市信息")

@RequestMapping(value="addStudent",method=RequestMethod.POST)

public String addCity(@RequestBody City city) {

cities.put(city.getId().toString(), city);

return "add city successfully";

}

@ApiOperation(value="删除一个城市",notes="根据id删除一个城市")

@ApiImplicitParam(name="city",value="要删除的城市信息")

@RequestMapping(value="delStudent",method=RequestMethod.DELETE)

public String delCity(@RequestBody City city) {

cities.remove(city.getId().toString());

return "remove city successfully";

}

@ApiOperation(value="查询所有城市")

@ApiImplicitParam(name="city",value="查詢所有城市")

@RequestMapping(value="getAllCity",method=RequestMethod.GET)

public String getAllCity(@RequestBody City city) {

return JSONObject.toJSONString(cities);

}

}

  • 启动spring boot访问http://localhost:8080/swagger-ui.html,即可简单如下页面
  • 总结:swagger基于restful风格的请求方式,不仅可以应用到实际开发中,还可用于接口测试、生成了一个完善的api说明!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值