Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。可用于:1.接口的文档在线自动生成、2.功能测试。

首先创建一个简单的maven项目,整合swagger一定要注意springboot与swagger的版本要适配,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>swagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>swagger</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

项目的目录如下所示,创建swagger配置文件,具体内容如下,包自己导入。

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();

    }
    private ApiInfo webApiInfo(){
         return new ApiInfoBuilder()
         .title("API文档")
         .description("接口定义")
         .version("1.0")
         .contact(new Contact("mzz", "http://www.baidu.com",
                "1345656307@qq.com"))
         .build();
         }
}

 数据库信息:

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  `sex` varchar(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(255) DEFAULT NULL COMMENT '地址',
  `phone` varchar(20) DEFAULT NULL COMMENT '电话',
  `create_time` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8


insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('2','张三','22','男','上海市','13867675656','2020-12-26');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('3','李四','20','男','合肥市','13978786565','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('5','赵柳','20','男','南京市','13978786565','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('6','钱望','22','男','深圳市','13867675656','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('7','李云','20','男','合肥市','13978786565','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('8','张傅','22','男','上海市','13867675656','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('9','李青','20','男','合肥市','13978786565','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('10','王二发','22','男','昆明市','13867675656','2020-11-18');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('12','王得贵','22','女','成都市','13867674565','2022-05-10');
insert into `user` (`id`, `name`, `age`, `sex`, `address`, `phone`, `create_time`) values('13','lih','23','男','我的粉丝的方式电池','12345678901','2022-05-09');

数据库:

 application.properties配置文件:

# 服务端口
server.port=8080

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/users?serverTimezone=GMT%2B8&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=

mybatis.mapper-locations=classpath:mapper/*.xml

#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

entity部分代码,使用lombok注解:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
    private String sex;
    private String address;
    private String phone;
    private String createTime;
}

mapper部分代码,只简单的写了二个方法:

public interface UserMapper {

    //根据id查询
    public User getUserById(int id);

    //查询所有
    public List<User> getAllUser();



}

service及实现类部分代码:(代码跟mapper差不多,遵循规范最好写一下)

public interface UserService {

    //根据id查询
    public User getUserById(int id);

    //查询所有
    public List<User> getAllUser();


}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(int id) {
        User user = userMapper.getUserById(id);
        return user;
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
    }

}

xml部分代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.swagger.mapper.UserMapper">

    <select id="getUserById" resultType="com.example.swagger.entity.User">
        select id,name,age,sex,address,phone,create_time from user where id = #{id}
    </select>

    <select id="getAllUser" parameterType="list" resultType="com.example.swagger.entity.User">
        select id,name,age,sex,address,phone,create_time from user
    </select>


</mapper>

controller代码:

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "id获取用户信息")
    @GetMapping("{id}")
    public User getUserById(@PathVariable("id") int id){
        return userService.getUserById(id);
    }

    @ApiOperation(value = "获取所有用户信息")
    @GetMapping("/allUser")
    public List<User> getAllUser(){
        return userService.getAllUser();
    }

}

启动类(注意注解):

@SpringBootApplication
@MapperScan("com.example.swagger.mapper")
public class SwaggerApplication {

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

}

最后启动项目,输入地址http://localhost:8080/swagger-ui.html#/,出现该页面表示swagger整合成功。

点击对应的接口进行测试:

 

1.查询所有用户信息:

2.通过id查询用户

 所有结果与数据库结果对应,swagger整合成功,测试成功。

注:上述entity,mapper,service以及xml等都可以通过mybatis-plus来实现。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐