在 Spring Boot 项目中整合 Knife4j 以支持查询、分页查询和 XML 方式查询的功能,通常需要以下几个步骤。下面将详细介绍如何实现这些功能。
确保在 pom.xml
中添加 Knife4j 和相关的 Spring Boot Starter 依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version> <!-- 根据需要替换为最新版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
集成knife4j
package com.example.demo1.ghy.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
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.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// apiInfo():配置 API 的一些基本信息,比如:文档标题title,文档描述description,文档版本号version
.apiInfo(apiInfo())
// select():生成 API 文档的选择器,用于指定要生成哪些 API 文档
.select()
// apis():指定要生成哪个包下的 API 文档
.apis(RequestHandlerSelectors.basePackage("com.example.demo1.ghy.controller"))
// paths():指定要生成哪个 URL 匹配模式下的 API 文档。这里使用 PathSelectors.any(),表示生成所有的 API 文档。
.paths(PathSelectors.any())
.build();
}
private static final String API_TILE="xx项目";
//文档信息配置
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 文档标题
.title(API_TILE)
// 文档描述信息
.description("xxx在线API文档")
// 文档版本号
.version("1.0")
.build();
}
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
创建一个实体类以及对应的表结构, User
:
@Data
@TableName("user")
public class User {
@TableId
private Long userId;
private String username;
private String email;
private String registrationDate;
private String status;
}
-- auto-generated definition
create table user
(
user_id int auto_increment
primary key,
username varchar(50) not null,
email varchar(100) not null,
registration_date datetime default CURRENT_TIMESTAMP null,
status enum ('活跃', '禁用') default '活跃' null,
constraint email
unique (email)
);
3.控制器
package com.example.demo1.ghy.controller;
import com.example.demo1.ghy.pojo.User;
import com.example.demo1.ghy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.list();
}
@GetMapping("/pageUsers")
public List<User> getPageUsers() {
return userService.getUsersPage(1,5);
}
@GetMapping("/test")
public int tests(int pageNum) {
System.out.println("pageNum: " + pageNum);
return pageNum;
}
}
4.服务层实现类
package com.example.demo1.ghy.service.imp;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo1.ghy.mapper.UserMapper;
import com.example.demo1.ghy.pojo.User;
import com.example.demo1.ghy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> getUsersPage(int pageNum, int pageSize) {
return userMapper.ghySelectPage(pageNum, pageSize);
}
}
5.Mapper层
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo1.ghy.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user LIMIT #{pageSize} OFFSET #{pageNum}")
List<User> ghySelectPage(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize);
User findById(Long userId);
void insertUser(User user);
void updateUserStatus(Long userId, String status);
void deleteUser(Long userId);
List<User> findAll();
}
对应XML文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-mapper-3.5.0.dtd">
<mapper namespace="com.example.demo1.ghy.mapper.UserMapper">
<!-- 查询用户 -->
<select id="findById" resultType="com.example.demo1.ghy.pojo.User">
SELECT * FROM users WHERE user_id = #{userId}
</select>
<!-- 插入用户 -->
<insert id="insertUser" parameterType="com.example.demo1.ghy.pojo.User">
INSERT INTO users (username, em ail, registration_date, status)
VALUES (#{username}, #{email}, #{registrationDate}, #{status})
</insert>
<!-- 更新用户状态 -->
<update id="updateUserStatus" parameterType="map">
UPDATE users
SET status = #{status}
WHERE user_id = #{userId}
</update>
<!-- 删除用户 -->
<delete id="deleteUser" parameterType="Long">
DELETE FROM users WHERE user_id = #{userId}
</delete>
<!-- 查询所有用户 -->
<select id="findAll" resultType="com.example.demo1.ghy.pojo.User">
SELECT * FROM users
</select>
</mapper>