Springboot+AOP實(shí)現(xiàn)時間參數(shù)格式轉(zhuǎn)換
前言
場景
前端傳過來的時間參數(shù),我們后端自定義時間格式轉(zhuǎn)化使用,想轉(zhuǎn)成什么就轉(zhuǎn)成什么。
不同業(yè)務(wù)場景,跟前端對接,一種控件基本時間參數(shù)是固定格式的,為了避免前端去轉(zhuǎn)換時間參數(shù)的格式,跟前端約定好,讓他們固定傳遞一種格式,后端自己看需求轉(zhuǎn)換格式使用即可。
效果
① 從 yyyy-MM-dd HH:mm:ss 轉(zhuǎn)換成 yyyy-MM-dd 使用:

② 從 yyyyMMddHHmmss 轉(zhuǎn)換成 yyyy-MM-dd HH:mm:ss 使用:

③不再舉例,其實(shí)就是自己想怎么轉(zhuǎn)就怎么轉(zhuǎn)。
實(shí)戰(zhàn)
pom.xml (aop依賴、lombok依賴):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>核心(自定義注解+攔截器):

自定義注解一
DateField.java
用途: 用于標(biāo)記哪個字段需要進(jìn)行時間格式轉(zhuǎn)換,配置舊格式,新格式(都可寫默認(rèn)值)。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author: JCccc
* @Date: 2022-4-11 18:45
* @Description:
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DateField {
String oldPattern() default DateUtil.YYYY_MM_DD_HH_MM_SS;
//新格式可以寫默認(rèn)也可以不寫,如果業(yè)務(wù)比較固定,那么新時間格式和舊時間格式都可以固定寫好
String newPattern() default "";
}自定義注解二
NeedDateFormatConvert.java
用途: 用于標(biāo)記哪個接口需要進(jìn)行AOP方式 時間格式轉(zhuǎn)換。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author: JCccc
* @Date: 2022-4-11 18:44
* @Description:
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedDateFormatConvert {
}攔截器
DateFormatAspect.java
用途: 核心轉(zhuǎn)換實(shí)現(xiàn)邏輯。
import com.jctest.dotestdemo.util.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* @Author: JCccc
* @Date: 2022-4-11 18:57
* @Description:
*/
@Aspect
@Component
public class DateFormatAspect {
private static Logger log = LoggerFactory.getLogger(DateFormatAspect.class);
@Pointcut("@annotation(com.jctest.dotestdemo.aop.dateFormat.NeedDateFormatConvert)")
public void pointCut() {
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//轉(zhuǎn)換
dateFormat(joinPoint);
return joinPoint.proceed();
}
public void dateFormat(ProceedingJoinPoint joinPoint) {
Object[] objects = null;
try {
objects = joinPoint.getArgs();
if (objects.length != 0) {
for (int i = 0; i < objects.length; i++) {
//當(dāng)前只支持判斷對象類型參數(shù)
convertObject(objects[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("參數(shù)異常");
}
}
/**
* 轉(zhuǎn)換對象里面的值
*
* @param obj
* @throws IllegalAccessException
*/
private void convertObject(Object obj) throws IllegalAccessException {
if (Objects.isNull(obj)) {
log.info("當(dāng)前需要轉(zhuǎn)換的object為null");
return;
}
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
boolean containFormatField = field.isAnnotationPresent(DateField.class);
if (containFormatField) {
//獲取訪問權(quán)
field.setAccessible(true);
DateField annotation = field.getAnnotation(DateField.class);
String oldPattern = annotation.oldPattern();
String newPattern = annotation.newPattern();
Object dateValue = field.get(obj);
if (Objects.nonNull(dateValue) && StringUtils.hasLength(oldPattern) && StringUtils.hasLength(newPattern)) {
String newDateValue = DateUtil.strFormatConvert(String.valueOf(dateValue), oldPattern, newPattern);
if (Objects.isNull(newDateValue)){
log.info("當(dāng)前需要轉(zhuǎn)換的日期數(shù)據(jù)轉(zhuǎn)換失敗 dateValue = {}",dateValue.toString());
throw new RuntimeException("參數(shù)轉(zhuǎn)換異常");
}
field.set(obj, newDateValue);
}
}
}
}
}工具類
DateUtil.java
用途: 時間格式轉(zhuǎn)換函數(shù)、定義各種時間格式。
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @Author: JCccc
* @Date: 2022-4-1 14:48
* @Description:
*/
@Slf4j
public class DateUtil {
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM = "yyyy-MM";
public static final String YYYY = "yyyy";
public static final String MM = "MM";
public static final String DD = "dd";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String YYYYMMDD = "yyyyMMdd";
/**
* 指定日期格式轉(zhuǎn)換
*
* @param dateStr
* @param oldPattern
* @return
*/
public static String strFormatConvert(String dateStr, String oldPattern,String newPattern) {
try {
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern(oldPattern);
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern(newPattern);
return LocalDateTime.parse(dateStr, oldFormatter).format(newFormatter);
} catch (Exception e) {
log.error("strToDate is Exception. e:", e);
return null;
}
}
}使用
UserQueryVO.java
import com.jctest.dotestdemo.aop.dateFormat.DateField;
import com.jctest.dotestdemo.util.DateUtil;
import lombok.Data;
import java.io.Serializable;
/**
* @Author: JCccc
* @Date: 2022-4-1 14:48
* @Description:
*/
@Data
public class UserQueryVO implements Serializable {
/**
* 開始時間
*/
@DateField(oldPattern =DateUtil.YYYY_MM_DD_HH_MM_SS, newPattern = DateUtil.YYYY_MM_DD)
private String startDate;
/**
* 結(jié)束時間
*/
@DateField(oldPattern =DateUtil.YYYY_MM_DD_HH_MM_SS,newPattern = DateUtil.YYYY_MM_DD)
private String endDate;
}接口
import com.jctest.dotestdemo.aop.dateFormat.NeedDateFormatConvert;
import com.jctest.dotestdemo.vo.UserQueryVO;
import org.springframework.web.bind.annotation.*;
/**
* @Author: JCccc
* @Date: 2022-4-18 11:52
* @Description:
*/
@RestController
public class UserController {
@NeedDateFormatConvert
@PostMapping("/test")
public String test( @RequestBody UserQueryVO userQueryVO){
System.out.println("時間格式轉(zhuǎn)化完成:");
System.out.println(userQueryVO.getStartDate());
System.out.println(userQueryVO.getEndDate());
return userQueryVO.toString();
}
}調(diào)用


以上就是Springboot+AOP實(shí)現(xiàn)時間參數(shù)格式轉(zhuǎn)換的詳細(xì)內(nèi)容,更多關(guān)于Springboot時間格式轉(zhuǎn)換的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java mysql數(shù)據(jù)庫并進(jìn)行內(nèi)容查詢實(shí)例代碼
這篇文章主要介紹了Java mysql數(shù)據(jù)庫并進(jìn)行內(nèi)容查詢實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-11-11
Java語言描述存儲結(jié)構(gòu)與鄰接矩陣代碼示例
這篇文章主要介紹了Java語言描述存儲結(jié)構(gòu)與鄰接矩陣代碼示例,涉及Java存儲結(jié)構(gòu),鄰接矩陣,鄰接表的介紹與比較,然后分享了鄰接矩陣的Java實(shí)現(xiàn)等相關(guān)內(nèi)容,具有一定借鑒價值,需要的朋友可以參考。2017-11-11
PowerJob的HashedWheelTimer工作流程源碼解讀
這篇文章主要為大家介紹了PowerJob的HashedWheelTimer工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
SpringBoot靜態(tài)資源與首頁配置實(shí)現(xiàn)原理深入分析
最近在做SpringBoot項(xiàng)目的時候遇到了“白頁”問題,通過查資料對SpringBoot訪問靜態(tài)資源做了總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10
Mybatis-plus selectByMap條件查詢方式
這篇文章主要介紹了Mybatis-plus selectByMap條件查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot返回long,前端接收進(jìn)度丟失,@JsonSerialize不生效問題
這篇文章主要介紹了SpringBoot返回long,前端接收進(jìn)度丟失,@JsonSerialize不生效問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
java評論、回復(fù)功能設(shè)計與實(shí)現(xiàn)方法
很多項(xiàng)目或者系統(tǒng)都有評論或者回復(fù)的需求,但評論回復(fù)的實(shí)現(xiàn)往往都比較復(fù)雜,也不好實(shí)現(xiàn),下面這篇文章主要給大家介紹了關(guān)于java評論、回復(fù)功能設(shè)計與實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2022-06-06

