当前位置: 首页 > news >正文

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

背景

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.lryc.cn/news/443045.html

相关文章:

  • Spring Boot实战:使用@Import进行业务模块自动化装配
  • Golang | Leetcode Golang题解之第415题字符串相加
  • 5. 数字证书与公钥基础设施
  • Centos中关闭swap分区,关闭内存交换
  • leetcode练习 二叉树的最大深度
  • Scrapy爬虫框架 Items 数据项
  • weblogic CVE-2018-2894 靶场攻略
  • 百易云资产管理运营系统 ticket.edit.php SQL注入漏洞复现
  • C++(2)进阶语法
  • 解决Hive乱码问题
  • Streamlit:使用 Python 快速开发 Web 应用
  • C#基础(11)函数重载
  • 堆栈指针寄存器SP的初值是多少?执行PUSH AX命令后,SP的值是多少?执行POP BX后,SP的值是多少?为什么答案给的是200,202,200。
  • python爬虫初体验(二)
  • 细说渗透测试:阶段、流程、工具和自动化开源方案
  • redis 十大应用场景
  • 信息安全数学基础(15)欧拉定理
  • sar(1) command
  • 掌握 JavaScript 中的函数表达式
  • OpenGL 原生库6 坐标系统
  • LabVIEW提高开发效率技巧----VI服务器和动态调用
  • 求1000以内所有恰好能分解成10组两个素数之和
  • Webpack 和 Vite 的区别
  • C++——初步认识C++和namespace的用法
  • LeetCode118:杨辉三角
  • 介绍一下大模型或者多模态?
  • 深度学习之图像数据集增强(Data Augmentation)
  • 小程序与APP的区别
  • Linux Kernel Makefiles 编译标志详解
  • 数据可视化pyecharts——数据分析(柱状图、折线图、饼图)