欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot+AOP實(shí)現(xiàn)時間參數(shù)格式轉(zhuǎn)換

 更新時間:2022年04月29日 11:12:11   作者:小目標(biāo)青年  
前端傳過來的時間參數(shù),后端可以自定義時間格式轉(zhuǎn)化使用,這樣想轉(zhuǎn)成什么就轉(zhuǎn)成什么。本文將利用自定義注解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中使用異或運(yùn)算符實(shí)現(xiàn)加密字符串

    Java中使用異或運(yùn)算符實(shí)現(xiàn)加密字符串

    這篇文章主要介紹了Java中使用異或運(yùn)算符實(shí)現(xiàn)加密字符串,本文直接給出實(shí)現(xiàn)代碼,以及運(yùn)算結(jié)果加密實(shí)例,需要的朋友可以參考下
    2015-06-06
  • BeanUtils.copyProperties復(fù)制屬性失敗的原因及解決方案

    BeanUtils.copyProperties復(fù)制屬性失敗的原因及解決方案

    這篇文章主要介紹了BeanUtils.copyProperties復(fù)制屬性失敗的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 最新版Eclipse安裝、配置圖文教程詳解

    最新版Eclipse安裝、配置圖文教程詳解

    這篇文章主要介紹了新版Eclipse安裝、配置,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • Java之Error與Exception的區(qū)別案例詳解

    Java之Error與Exception的區(qū)別案例詳解

    這篇文章主要介紹了Java之Error與Exception的區(qū)別案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • Maven項(xiàng)目引用第三方j(luò)ar包找不到類ClassNotFoundException

    Maven項(xiàng)目引用第三方j(luò)ar包找不到類ClassNotFoundException

    這篇文章主要為大家介紹了Maven項(xiàng)目引用第三方j(luò)ar包找不到類ClassNotFoundException解決及原因分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • Spring boot中PropertySource注解的使用方法詳解

    Spring boot中PropertySource注解的使用方法詳解

    這篇文章主要給大家介紹了關(guān)于Spring boot中PropertySource注解的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-12-12
  • 淺談JAVA 異常對于性能的影響

    淺談JAVA 異常對于性能的影響

    Java的異常處理為什么會影響性能?異常開銷很大。那么,這是不是就意味著您不該使用異常?當(dāng)然不是。但是,何時應(yīng)該使用異常,何時又不應(yīng)該使用異常呢?不幸的是,答案不是一下子就說得清楚的,我們來詳細(xì)探討下。
    2015-05-05
  • Android bdflow數(shù)據(jù)庫神器的使用

    Android bdflow數(shù)據(jù)庫神器的使用

    這篇文章主要介紹了Android bdflow數(shù)據(jù)庫神器的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • Java中String和StringBuffer及StringBuilder?有什么區(qū)別

    Java中String和StringBuffer及StringBuilder?有什么區(qū)別

    這篇文章主要介紹了Java中String和StringBuffer及StringBuilder?有什么區(qū)別,String?是?Java?語言非?;A(chǔ)和重要的類,更多相關(guān)內(nèi)容需要的小伙伴可以參考下面文章內(nèi)容
    2022-06-06
  • java方法實(shí)現(xiàn)簡易ATM功能

    java方法實(shí)現(xiàn)簡易ATM功能

    這篇文章主要為大家詳細(xì)介紹了用java方法實(shí)現(xiàn)簡易ATM功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-04-04

最新評論