Spring Boot与swagger对刚接触JAVA的朋友来说可能熟悉又陌生,Spring Boot不需要配置繁琐的xml文件,只需要引入相关依赖,简单易上手。而swagger是一个强大的API文档工具,可以极大的提高工作效率。
建立一个maven工程。工程目录如下:
配置pom文件,主要引入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>
在application.properties中进行连接数据库配置:
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
数据访问层:
package com.example.swagger.dao;
import com.example.swagger.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserDao {
@Insert("insert into message(id,name,number) values (#{id},#{name},#{number})")
void addUser(User user);
@Update("update message set name=#{name},number=#{number} where id=#{id}")
void updateUser(User user);
@Delete("delete from message where id=#{id}")
void deleteUser(int id);
@Select("SELECT id,name,number FROM message where name=#{userName}")
User findByName(String userName);
@Select("SELECT id,name,number FROM message")
List<User> findAll();
}
实体类层
package com.example.swagger.entity;
public class User {
private int id;
private String name;
private String number;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", number='" + number + '\'' +
'}';
}
}
服务层:
package com.example.swagger.service;
import com.example.swagger.entity.User;
import java.util.List;
public interface UserService {
boolean addUser (User user);
boolean updateUser(User user);
boolean deleteUser (int id);
User findUserByName(String userName);
List<User> findAll();
}
Serviceimpl
package com.example.swagger.service.impl;
import com.example.swagger.dao.UserDao;
import com.example.swagger.entity.User;
import com.example.swagger.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public boolean addUser(User user) {
boolean flag=false;
try{
userDao.addUser(user);
flag=true;
}catch(Exception e){
System.out.println("新增失败!");
e.printStackTrace();
}
return flag;
}
@Override
public boolean updateUser(User user) {
boolean flag=false;
try{
userDao.updateUser(user);
flag=true;
}catch(Exception e){
System.out.println("修改失败!");
e.printStackTrace();
}
return flag;
}
@Override
public boolean deleteUser(int id) {
boolean flag=false;
try{
userDao.deleteUser(id);
flag=true;
}catch(Exception e){
System.out.println("删除失败!");
e.printStackTrace();
}
return flag;
}
@Override
public User findUserByName(String userName) {
return userDao.findByName(userName);
}
@Override
public List<User> findAll() {
return userDao.findAll();
}
}
Controller
package com.example.swagger.web;
import java.util.List;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.swagger.entity.User;
import com.example.swagger.service.UserService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/api")
public class userRestController {
@Autowired
private UserService userService;
@ApiOperation(value = "添加新的信息")//添加中文注释
@RequestMapping(value = "/user", method = RequestMethod.POST)
public boolean addUser(@RequestBody User user){
System.out.println("开始新增。。。");
return userService.addUser(user);
}
@ApiOperation(value = "更新信息")
@RequestMapping(value = "/user", method = RequestMethod.PUT)
public boolean updateUser(@RequestBody User user) {
System.out.println("开始更新...");
return userService.updateUser(user);
}
@ApiOperation(value = "根据id删除信息")
@RequestMapping(value = "/user", method = RequestMethod.DELETE)
public boolean delete(@RequestParam(value = "userId", required = true) int userId) {
System.out.println("开始删除...");
return userService.deleteUser(userId);
}
@ApiOperation(value = "根据姓名查询信息")
@RequestMapping(value = "/username", method = RequestMethod.GET)
public User findByUserName(@RequestParam(value = "userName", required = true) String userName) {
System.out.println("开始查询...");
return userService.findUserByName(userName);
}
@ApiOperation(value = "查询全部信息")
@RequestMapping(value = "/userAll", method = RequestMethod.GET)
public List<User> findByUserAge() {
System.out.println("开始查询所有数据...");
return userService.findAll();
}
}
Swagger层(必须跟启动类在同一目录下)
package com.example.swagger;
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 //开启swagger2
public class SwaggerConfiguration {
@Bean //配置了swagger的docket的bean实例
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors,配置要扫描接口的方式
//basePackeg:指定包扫描
//any():扫描全部
//none():不扫描
//withClassAnnotation:扫描类上的注解
.apis(RequestHandlerSelectors.basePackage("com.example.swagger.web"))
//path():过滤什么路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() { //配置swagger信息 = apiInfo
return new ApiInfoBuilder().title("增删查改")
.description("数据库表中信息的修改")
.license("Apache 2.0")
.version("1.0")
.build();
}
}
启动类
package com.example.swagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SwaggerDemoApplication {
public static void main( String[] args ){
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
运行结果:
做一个简单的验证,查询一下全部信息:
至此,项目算是搭建完成。
1.我们可以通过Swagger给一些比较难理解的属性或者接口增加注释信息,通过@Api等系列注解,来方便测试人员或者前端人员更好的理解。
例如:@ApiOperation(value = “添加新的信息”)//添加中文注释
2.接口文档实时更新。
3.可以接口的进行在线测试。
4.可以配置多个docket实例,互不干扰,更好的进行合作开发。
public class SwaggerConfiguration {
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}