http://start.spring.io/生成springboot工程
引入maven依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>加载swagger2配置
@Configuration @EnableSwagger2 public class SwaggerConfig { @Autowired Environment env; @Bean public Docket createRestApi(ApiInfo apiInfo) { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo) .select() .apis(RequestHandlerSelectors.basePackage(env.getProperty("swagger.scan"))) .paths(PathSelectors.any()) .build(); } @Bean public ApiInfo apiInfo() { return new ApiInfoBuilder() .title(env.getProperty("swagger.title")) .description(env.getProperty("swagger.description")) .version(env.getProperty("swagger.version")) .build(); } }application.yml
spring: application: name: swagger-test server: port: 8080 context-path: /api swagger: scan: com.swagger.test title: 用户service API description: 用户service API version: 1.0.0controller
@RestController @RequestMapping("/user") @Api(value="用户controller",description="用户操作",tags={"用户操作接口"}) public class UserController { @GetMapping("/get") @ApiOperation(value = "获取用户接口",notes = "获取用户接口notes",response = String.class) public String get(@ApiParam(name = "userName",value = "用户名",required = true) @RequestParam("userName") String userName){ return "返回值:"+userName; } @PostMapping("/post") @ApiOperation(value = "获取用户接口Post",notes = "获取用户接口notes Post",response = UserForm.class) public UserForm post(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) UserForm userForm){ return userForm; } }
form
@ApiModel(description = "用户from") public class UserForm { @ApiModelProperty(value = "用户名",name = "userName",required = true) private String userName; @Override public String toString() { return "UserForm{" + "userName='" + userName + '\'' + '}'; } /** * Getter method for property <tt>userName</tt> * * @return property value of userName */ public String getUserName() { return userName; } /** * Setter method for property <tt>userName</tt>. * * @param userName value to be assigned to property userName */ public void setUserName(String userName) { this.userName = userName; } }
启动 访问:http://localhost:8080/api/swagger-ui.html
例子下载地址:http://download.csdn.net/download/zyj_2012/10191998