一,在pom.xml文件中添加swagger依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
二,添加swagger配置文件
* Swagger配置文件
* 通过http://localhost:端口号/swagger-ui.html 即可访问查看效果
* 没有该类Swagger默认也是可以访问的
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
public static final String VERSION = "1.0.1";
public static final String AUTHOR = "lxw";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.lxw.api_project.controller"))
.paths(PathSelectors.regex("/.*"))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.ignoredParameterTypes(ApiIgnore.class)
.enableUrlTemplating(false)
.tags(new Tag("Account", "账号模块"));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("服务端接口搭建API文档")
.version(VERSION)
.contact(new Contact(AUTHOR, "http://www.baidu.com", "")).build();
}
}
三,在application中通过注解启动swagger
@MapperScan("com.lxw.api_project")
@EnableSwagger2
@SpringBootApplication
public class ApiProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ApiProjectApplication.class, args);
}
}
四,在controller接口中使用,注释中描述使用步骤
@RestController
@RequestMapping(value = "/user")
@Api(tags = {"Account"})
public class UserController {
@Autowired
private UserService mUserService;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@ApiOperation(value = "注册")
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public Object registration(@RequestParam(value = "userName") @ApiParam("用户名") String userName
, @RequestParam(value = "password") @ApiParam("密码") String password
, @RequestParam(value = "orderId") @ApiParam("订单ID") String orderId) {
mUserService.addUser(userName, bCryptPasswordEncoder.encode(password), imoocId, orderId);
return "registration success.";
}
}
五,完成后运行 http://localhost:5088/swagger-ui.html