基于Jeecg-boot开发系统--后端篇

server/2024/9/22 4:57:31/

背景

Jeecg-boot是一个后台管理系统,其提供能很多基础的功能,我希望在不修改jeecg-boot代码的前提下增加自己的功能。经过几天的折腾终于搞定了。
首先是基于jeecg-boot微服务的方式来扩展的,jeecg-boot微服务本身的搭建过程就不讲了,主要讲增加的功能如何与jeecg-boot集成在一起。先说步骤:

1.依赖

<parent><groupId>org.jeecgframework.boot</groupId><artifactId>jeecg-boot-parent</artifactId><version>3.7.0</version>
</parent><dependency><groupId>org.jeecgframework.boot</groupId><artifactId>jeecg-boot-starter-cloud</artifactId>
</dependency>
<dependency><groupId>org.jeecgframework.boot</groupId><artifactId>jeecg-boot-base-core</artifactId>
</dependency>
<dependency><groupId>org.jeecgframework.boot</groupId><artifactId>jeecg-system-cloud-api</artifactId>
</dependency>
<!-- 加载了上面几个 jeecg-boot核心的就有了,包括授权之类的。  其他按需加载 -->

2.配置

@Slf4j
@EnableFeignClients
@SpringBootApplication
@MapperScan(value={"com.snail.**.mapper*","org.jeecg.**.mapper*"})  // mybatis集成
@ComponentScan(value= {"com.snail","org.jeecg"},excludeFilters = {@ComponentScan.Filter(type= FilterType.ASSIGNABLE_TYPE,classes = {Swagger2Config.class})}) // 重写Swagger2Config
public class SnailDemoApplication extends SpringBootServletInitializer implements CommandLineRunner {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(SnailDemoApplication.class);}public static void main(String[] args) throws UnknownHostException {ConfigurableApplicationContext application = SpringApplication.run(SnailDemoApplication.class, args);Environment env = application.getEnvironment();String ip = InetAddress.getLocalHost().getHostAddress();String port = env.getProperty("server.port");String path = StrUtil.blankToDefault(env.getProperty("server.servlet.context-path"),"");log.info("\n----------------------------------------------------------\n\t" +"Application Jeecg-Boot is running! Access URLs:\n\t" +"Local: \t\thttp://localhost:" + port + path + "/\n\t" +"External: \thttp://" + ip + ":" + port + path + "/\n\t" +"Swagger文档: \thttp://" + ip + ":" + port + path + "/doc.html\n" +"----------------------------------------------------------");}@Overridepublic void run(String... args) throws Exception {BaseMap params = new BaseMap();params.put(GlobalConstants.HANDLER_NAME, GlobalConstants.LODER_ROUDER_HANDLER);//刷新网关redisTemplate.convertAndSend(GlobalConstants.REDIS_TOPIC_NAME, params);}
}

3. swagger 集成

a. 系统管理–>网关路由 : 增加一条记录。(不增加的话,无法在网关上显示).

b. 重写swagger配置文件,主要用于修改swagger上的显示信息及修改扫描的包,若使用的包是org.jeecg又不用改显示信息的话,则不需要重写

c. 若重写了Swagger2Config,则需要禁用原来的Swagger2Config类。在启动类通过excludeFilters排除即可。

package com.snail.demo.config;import springfox.documentation.RequestHandler;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.constant.CommonConstant;
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.context.annotation.Import;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.stream.Collectors;@EnableSwagger2WebMvc
@Configuration
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Config implements WebMvcConfigurer {/*** 显示swagger-ui.html文档展示页,还必须注入swagger资源:** @param registry*/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}/*** swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等** @return Docket*/@Bean(value = "defaultApi2", autowireCandidate = true)public Docket defaultApi2() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()//此包路径下的类,才生成接口文档
//                .apis(RequestHandlerSelectors.basePackage("com.snail")) // 单个包,使用这个就可以了,.apis(basePackage("com.snail;org.jeecg"))  // 需要多个包时使用这个方式//加了ApiOperation注解的类,才生成接口文档.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build().securitySchemes(Collections.singletonList(securityScheme())).securityContexts(securityContexts()).globalOperationParameters(setHeaderToken()).pathMapping("/jeecg-demo2");}public static Predicate<RequestHandler> basePackage(final String basePackage) {return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);}private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {return input -> {// 循环判断匹配for (String strPackage : basePackage.split(";")) {boolean isMatch = input.getPackage().getName().startsWith(strPackage);if (isMatch) {return true;}}return false;};}private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {return Optional.fromNullable(input.declaringClass());}/**** oauth2配置* 需要增加swagger授权回调地址* http://localhost:8888/webjars/springfox-swagger-ui/o2c.html* @return*/@Bean(autowireCandidate = true)SecurityScheme securityScheme() {return new ApiKey(CommonConstant.X_ACCESS_TOKEN, CommonConstant.X_ACCESS_TOKEN, "header");}/*** JWT token** @return*/private List<Parameter> setHeaderToken() {ParameterBuilder tokenPar = new ParameterBuilder();List<Parameter> pars = new ArrayList<>();tokenPar.name(CommonConstant.X_ACCESS_TOKEN).description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(tokenPar.build());return pars;}/*** api文档的详细信息函数,注意这里的注解引用的是哪个** @return*/private ApiInfo apiInfo() {return new ApiInfoBuilder()// //大标题.title("测试测试")// 版本号.version("1.0")
//				.termsOfServiceUrl("NO terms of service")// 描述.description("后台API接口")// 作者.contact(new Contact("xxxx", "www.llf.com", "shui878412@126.com")).license("xxxx").licenseUrl("ccccc").build();}/*** 新增 securityContexts 保持登录状态*/private List<SecurityContext> securityContexts() {return new ArrayList(Collections.singleton(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("^(?!auth).*$")).build()));}private List<SecurityReference> defaultAuth() {AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];authorizationScopes[0] = authorizationScope;return new ArrayList(Collections.singleton(new SecurityReference(CommonConstant.X_ACCESS_TOKEN, authorizationScopes)));}/*** 解决springboot2.6 和springfox不兼容问题** @return*/@Bean()public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {return new BeanPostProcessor() {@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {if (bean instanceof WebMvcRequestHandlerProvider) {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);}}};}}

http://www.ppmy.cn/server/120128.html

相关文章

【计算机网络 - 基础问题】每日 3 题(七)

✍个人博客&#xff1a;Pandaconda-CSDN博客 &#x1f4e3;专栏地址&#xff1a;http://t.csdnimg.cn/fYaBd &#x1f4da;专栏简介&#xff1a;在这个专栏中&#xff0c;我将会分享 C 面试中常见的面试题给大家~ ❤️如果有收获的话&#xff0c;欢迎点赞&#x1f44d;收藏&…

目标检测YOLO系列算法——YOLOv1-YOLOv9详细介绍

YOLO&#xff08;You Only Look Once&#xff09;系列算法自2016年推出以来&#xff0c;已成为计算机视觉领域中目标检测的主流算法之一。YOLO的核心思想是将目标检测任务转化为一个回归问题&#xff0c;通过单次前向传播即可预测图像中的目标位置和类别。以下是YOLO系列算法的…

深度学习02-pytorch-09(pytorch完结篇)-基本使用介绍-线性回归案例

使用PyTorch的基本流程&#xff1a;数据准备&#xff1a;通过make_regression生成回归数据&#xff0c;使用 TensorDataset 和 DataLoader 来封装数据。 模型定义&#xff1a;使用 nn.Module 或内置层&#xff08;如 nn.Linear&#xff09;来定义模型结构。 损失函数和优化器…

HTTPS:构建安全通信的基石

HTTPS&#xff08;Hypertext Transfer Protocol Secure&#xff09;&#xff0c;作为互联网上安全通信的基石&#xff0c;通过在HTTP基础上引入SSL/TLS协议层&#xff0c;实现了数据传输的加密&#xff0c;确保了信息的机密性、完整性和真实性。这一过程涉及多个精细设计的步骤…

“浑水摸鱼”用俄语怎么说?柯桥小语种培训含有动物的成语翻译大盘点

虎头蛇尾 начать за здравие,а кончить заупокой 画龙点睛 вносить решающий штрих 画蛇添足 нарисовав змею,прибавить к ней ноги 浑水摸鱼 ловить рыбу в мутной…

数据结构:内部排序

文章目录 1. 前言1.1 什么是排序&#xff1f;1.2 排序的稳定性1.3 排序的分类和比较 2. 常见的排序算法3. 实现常见的排序算法3.1 直接插入排序3.2 希尔排序3.3 直接选择排序3.4 堆排序3.5 冒泡排序3.6 快速排序3.6.1 hoare思想3.6.2 挖坑法3.6.3 lomuto前后指针法3.6.4 非递归…

yolov5足球运动分析-速度分析-足球跟踪

足球分析项目 引言 在现代体育分析领域&#xff0c;利用先进的计算机视觉技术和机器学习模型对比赛视频进行深入解析已成为一种趋势。本项目旨在通过YOLO&#xff08;You Only Look Once&#xff09;这一顶级的人工智能目标检测模型来识别并跟踪足球比赛中的球员、裁判以及足球…

“一屏显江山”,激光显示重构「屏中世界」

【潮汐商业评论/原创】 2024年国庆期间&#xff0c;曾感动过无数国人的舞蹈诗剧《只此青绿》改编的同名电影即将上映&#xff0c;而这一次观众们不必走进电影院&#xff0c;在家里打开官方合作的海信激光电视也能享受到同等的视听效果&#xff0c;这是激光电视在观影场景领域的…