第一步:在pom.xml中添加依赖
<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>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.6</version>
</dependency>
第二步:swagger配置
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = {"com.wjs.demo.controller"})
public class SwaggerConfig {
@Bean
public Docket customDocket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact contact = new Contact("wjs",null,"278073309@qq.com");
return new ApiInfoBuilder()
.title("wjs项目API接口")
.description("API接口")
.contact(contact)
.version("1.1.0")
.build();
}
}
第三步:创建control包
第四步:WebMvcConfig
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
第五步:创建User实体类
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
第六步:创建UserController
@RestController
@Api(value = "用户模块",description = "用户模块的接口")
public class UserController {
private static List<User> users = new ArrayList<>();
static {
users.add(new User("张三","123456"));
users.add(new User("李四","654321"));
}
//获取用户列表的方法
@ApiOperation(value = "获取用户列表",notes = "获取所有用户的列表 ")
@GetMapping("/users")
public Object users(){
Map<Object,Object> map = new HashMap<>();
map.put("users",users);
return map;
}
@ApiOperation(value = "获取单个用户",notes = "根据ID查询某个用户的信息")
@ApiImplicitParam(value = "用户的ID",paramType = "path")
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id")int id){
return users.get(id);
}
@ApiOperation(value = "添加用户",notes = "根据传入的用户信息添加用户")
@ApiImplicitParam(value = "用户对象",paramType = "query")
@PostMapping("user")
public Object add(User user){
return users.add(user);
}
@ApiOperation(value = "删除用户",notes = "根据传入的用户ID删除对应的用户")
@ApiImplicitParam(value = "用户的ID",paramType = "path")
@DeleteMapping("/user/{id}")
public Object delete(@PathVariable("id")int id){
return users.remove(id);
}
}
第七步:运行,然后在浏览器上输入
localhost:8080/swagger-ui.html