首页 > 编程语言 >java项目(knife4j使用,静态资源未放在static资源包下,公共字段自动填充,Spring Cache与Spring Task)

java项目(knife4j使用,静态资源未放在static资源包下,公共字段自动填充,Spring Cache与Spring Task)

时间:2024-07-20 13:53:55浏览次数:13  
标签:knife4j 缓存 Spring Cache entity org import com annotation

Knife4j(生成接口文档)

使用swagger你只需要按照它的规范去定义接口及接口相关的信息,就可以做到生成接口文档,以及在线接口调试页面。官网:https://swagger.io/
Knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案。

使用方式

1、导入 knife4j的maven坐标

<dependency>
<groupld>com.github.xiaoymin</groupld>
<artifactld>knife4j-spring-boot-starter</artifactld>
<version>3.0.2</version>
</dependency>

2、在配置类中加入 knife4j相关配置

 @Bean
    public Docket docket() {
        log.info("准备生成接口文档");
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("xxx项目接口文档")//生成标题
                .version("2.0")//版本
                .description("xxx项目接口文档")//描述信息
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)//生成接口文档的信息
                .select()
                //指定生成接口需要扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

3、设置静态资源映射,否则接口文档页面无法访问

 protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始设置静态资源映");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

通过localhost:8080/doc.html就可以访问了

静态资源未放在static资源包下

可以创建一个配置类

WebMvcConfig类:

package com.example.reggie.Config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    /**
     * Description:设置静态资源映射
     * date: 2024-07-16 21:50
     *
     * @author: 努力敲代码的小火龙
     */


    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始进行静态资源映射、、、");
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }
}

这样就可以完成静态资源映射

公共字段自动填充

这四个字段就属于公共字段,为表中插入数据时就要向这些公共字段赋值

代码冗余、不便于后期维护

那我们该如何实现公共字段自动填充呢?

1、自定义注解 AutoFil,用于标识需要进行公共字段自动填充的方法

枚举:

自定义注解: 

package com.sky.annotation;

import com.sky.enumeration.OperationType;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {
    //数据库操作类型
    OperationType value();
}

2、自定义切面类 AutoFilAspect,统一拦截加入了 AutoFi 注解的方法,通过反射为公共字段赋值

 自定义切面类 AutoFilAspect:

package com.sky.Aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * Description: 切入点
     * date: 2024-07-18 13:38
     *
     * @author: 努力敲代码的小火龙
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    ;


    /**
     * Description:前置通知
     * date: 2024-07-18 13:42
     *
     * @author: 努力敲代码的小火龙
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException {
        log.info("开始进行公共字段自动填充...");
        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
        OperationType value = annotation.value();//获得数库操作类型
        //获取到当前被拦截的方法的参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];
        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //根据当前不同的操作类型,为对应的属性通过反射来赋值
        if (value == OperationType.INSERT) {
            try {
               Method setUpdateTime =entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                //通过反射为对象属性赋值
                setCreateTime.invoke(entity,now);
                setCreateUser.invoke(entity,currentId);
                setUpdateUser.invoke(entity,currentId);
                setUpdateTime.invoke(entity,now);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (value==OperationType.UPDATE) {
            try {
                Method setUpdateTime =entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateUser.invoke(entity,currentId);
                setUpdateTime.invoke(entity,now);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

3、在 Mapper 的方法上加入 AutoFil 注解

 

Spring Cache

Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。

Spring Cache 提供了一层抽象,底层可以切换不同的缓存实现,例如:EHCache、Caffeine、Redis

导入依赖

pom.xml

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

常用注解:  

@EnableCaching        开启缓存注解功能,通常加在启动类上
@Cacheable        在方法执行前先查询缓存中是否有数据,如果有数据则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中
@CachePut        将方法的返回值放到缓存中
@CacheEvict        将一条或多条数据从缓存中删除

@EnableCaching        开启缓存注解功能,通常加在启动类上


@Cacheable        在方法执行前先查询缓存中是否有数据,如果有数据则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中


@CachePut        将方法的返回值放到缓存中

这个id是从下面的返回值取到的

这个是取第一个参数的id

这个也是取第一个参数的id

下面是上面的这个的语法


@CacheEvict        将一条或多条数据从缓存中删除

删除一条数据 

 删除多条数据

Spring Task 

Spring Task 是Spring框架提供的任务调度工具,可以按照约定的时间自动执行某个代码逻辑。

定位:定时任务框架

作用:定时自动执行某段Java代码 

cron表达式

cron表达式其实就是一个字符串,通过cron表达式可以定义任务触发的时间

构成规则:分为6或7个域,由空格分隔开,每个域代表一个含义

每个域的含义分别为:秒、分钟、小时、日、月、周、年(可选)

可以用编辑器直接生成cron表达式

Spring Task使用步骤

导入maven坐标spring-context

启动类添加注解 @EnableScheduling开启任务调度

自定义定时任务类 

标签:knife4j,缓存,Spring,Cache,entity,org,import,com,annotation
From: https://blog.csdn.net/m0_46702681/article/details/140478013

相关文章

  • 观察者模式实战:Spring Boot中联动更新机制的优雅实现
    引言在许多应用系统中,我们经常需要处理多个表之间的关联更新问题。例如,在教育管理系统中,当学生的基本信息表中的年龄字段发生更改时,我们可能还需要同步更新学生档案表和学生成绩表中的相关信息。本文将通过一个具体的案例,介绍如何在SpringBoot项目中利用观察者模式来优雅地解......
  • Spring cloud 安全部署与性能优化
    Mr.NeoChen(陈景峯),netkiller,BG7NYT节选自《NetkillerSpringCloud手札》多维度架构-知乎​www.zhihu.com/club/1241768772601950208​编辑1.环境安装1.1.操作系统初始化操作系统按完成后,使用下面脚本做一次初始化curl-shttps://raw.githubusercontent.co......
  • SpringBoot+Vue的闲一品零食交易平台(前后端分离)
    技术栈JavaSpringBootMavenMySQLmybatisVueShiroElement-UI角色对应功能网站用户管理员项目功能截图......
  • SpringBoot+Vue的进存销管理系统(前后端分离)
    技术栈JavaSpringBootMavenMySQLmybatisVueShiroElement-UI角色对应功能管理员员工项目功能截图......
  • 基于Java Springboot餐厅点餐系统
    作者介绍:✌全网粉丝10W+本平台特邀作者、博客专家、CSDN新星计划导师、软件领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于项目实战✌一、作品包含源码+数据库+设计文档万字+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css......
  • 基于Java Springboot宠物管理系统
    作者介绍:✌全网粉丝10W+本平台特邀作者、博客专家、CSDN新星计划导师、软件领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于项目实战✌一、作品包含源码+数据库+设计文档万字+全套环境和工具资源+部署教程二、项目技术前端技术:Html、Css......
  • Memcached开发(七):使用Java进行操作
    目录1.安装与配置Memcached1.1安装Memcached1.2配置Memcached2.使用Java与Memcached进行交互2.1安装Java客户端2.2连接Memcached2.3基本操作2.3.1设置键值对2.3.2获取键值对2.3.3删除键值对2.3.4检查键是否存在2.3.5增加和减少数值2.4高级操作2.4.1......
  • Spring Book Club + java查询数据库 + 百万数据 + 同步Elasticsearch(ES)+ 多线程 + Fei
    @FeignClient(name="bwie-elastic")publicinterfaceEsFeign{@PostMapping("/add")publicResultadd(@RequestBodyArrayList<ResourceInfo>resourceInfo);}@RestControllerpublicclassUserControllerimplementsApplica......
  • 毕设项目:springboot+vue实现的在线求职平台
    一、前言    随着信息技术的飞速发展和互联网的普及,线上求职已成为众多求职者和企业招聘的重要渠道。为满足市场需求,我们利用SpringBoot和Vue技术栈,开发了一款功能全面、用户友好的在线求职平台。本文将对该平台的设计、实现及关键技术进行详细介绍。本文介绍基于spring......
  • springboot公寓租赁系统-计算机毕业设计源码03822
    目 录摘要1绪论1.1研究背景与意义1.2选题背景1.3论文结构与章节安排2 公寓租赁系统系统分析2.1可行性分析2.1.1技术可行性分析2.1.2经济可行性分析2.1.3法律可行性分析2.2系统功能分析2.2.1功能性分析2.2.2非功能性分析2.3系统用例......