SpringBoot集成SwaggerUI

Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目,实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,同时swagger-ui还可以测试spring restful风格的接口功能。其官方网站为:http://swagger.io/

项目环境:

  • jdk1.8
  • SpringBoot1.5.3
  • swagger2

效果图

SpringBoot集成SwaggerUI_第1张图片
效果图

首先添加依赖


    io.springfox
    springfox-swagger2
    2.6.1


    io.springfox
    springfox-swagger-ui
    2.6.1

将注解添加到WebConfiguration的类上。

@Configuration
@EnableSwagger2
public class WebConfiguration extends WebMvcConfigurerAdapter{
    
}

Springfox会和一组Docket协同工作,所以需要在类中定义为bean。

@SpringBootApplication
public class SpringbootSwaggerApplication {

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

    @Bean
    public Docket useApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .paths(path -> path.startsWith("/api/"))
                .build();
    }
}

Controller层

简单的curd接口。

@RestController
@RequestMapping("/api")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;


    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public List findAll() {
        return userInfoService.findAll();
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public UserInfo findOne(@PathVariable("id") String id) {
        return userInfoService.findOne(id);
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public UserInfo createUserInfo(UserInfo userInfo) {
        return userInfoService.save(userInfo);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public UserInfo updateUserInfo(@PathVariable("id") String id, UserInfo userInfo) {
        return userInfoService.update(id, userInfo);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable("id") String id) {
        userInfoService.delete(id);
    }
}

最简单的搭建方法到此结束,有兴趣的朋友的可以去浏览下官网

项目地址:https://github.com/huangbuhuan/springboot

你可能感兴趣的:(SpringBoot集成SwaggerUI)