美文网首页
Spring boot + Swagger 入门搭建

Spring boot + Swagger 入门搭建

作者: JL_0d88 | 来源:发表于2017-08-03 17:14 被阅读0次

导语:

Spring-Boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

特点

  • 创建独立的Spring应用程序
  • 嵌入的Tomcat,无需部署WAR文件
  • 简化Maven配置
  • 自动配置Spring
  • 提供生产就绪型功能,如指标,健康检查和外部配置
  • 绝对没有代码生成和对XML没有要求配置

创建Spring-boot项目

  1. 使用IDEA 选择Spring Initalizr -->Next


  2. 可以什么都不选,直接下一步


  3. 勾选web


  4. 完成创建


POM配置

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!--boot end-->

启动 Spring-Boot 项目

  • 创建 DomeController.java

      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      
      @SpringBootApplication
      public class DomeController {
      
         public static void main(String[] args) {
            SpringApplication.run(DomeController.class, args);
         }
      } 
    
  • 创建方法 helloSpringBoot

  •    @RequestMapping(value = "/hello")
      public String helloSpringBoot(){
          return "Hello SpringBoot";
      }
    
  • 在刚刚创建的项目中找到 DomeApplication.java 并启动它

  • 浏览器请求localhost:8080/dome/hello

Swagger

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。本文简单介绍了在项目中集成swagger的方法和一些常见问题。Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

学习之前我们需要做一点准备
  1. 创建User类
  2. Swagger2 服务类
  3. 创建UserController.java
  4. 启动SpringBoot
  5. 查看Swagger UI页面

引入POM

    <!--swagger start-->
    <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>

    <!--swagger end-->

创建User类

public class User implements Serializable{  
    private String name;
    private Integer age;
    private long id;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
} 

Swagger2 服务类

swagger-服务关键代码:必须和boot 服务启动类同一目录
import org.springframework.context.annotation.Bean;
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
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sanqiange"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
                
                .termsOfServiceUrl("http://blog.didispace.com/")
                .contact("dd")
                .version("1.0")
                .build();
    }

}

创建UserController.java

import com.sanqian.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping(value = "/users")// 通过这里配置使下面的映射都在/users下,可去除
public class UserController {
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    /**
     * @return
     * @ApiOperation 方法添加注释
     * @RequestMapping 指定方法路径
     */
    @ApiOperation(value = "获取用户列表",
            notes = "注释",
            httpMethod = "GET",
            nickname = "getUserList",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = {""}, method = RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    /**
     * @param user
     * @return
     * @ApiImplicitParam 注解来给参数增加说明
     */
    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息", httpMethod = "GET")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象", httpMethod = "DELETE")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }
}

启动SpringBoot

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CenterApplication {

   public static void main(String[] args) {
      SpringApplication.run(CenterApplication.class, args);
   }
}

查看Swagger UI页面

地址栏输入localhost:8080/swagger-ui.html#/

相关文章

网友评论

      本文标题:Spring boot + Swagger 入门搭建

      本文链接:https://www.haomeiwen.com/subject/ndwplxtx.html