免费爱碰视频在线观看,九九精品国产屋,欧美亚洲尤物久久精品,1024在线观看视频亚洲

      用了這個工具后,再也不寫 getter、setter 了

      用了這個工具后,再也不寫 getter、setter 了

      作者:DrLauPen 鏈接:https://juejin.cn/post/7103135968256851976

      前言

      相信絕大多數(shù)的業(yè)務(wù)開發(fā)同學(xué),日常的工作都離不開寫 getter、setter 方法。要么是將下游的 RPC 結(jié)果通過getter、setter 方法進(jìn)行獲取組裝。要么就是將自己系統(tǒng)內(nèi)部的處理結(jié)果通過 getter、setter 方法處理成前端所需要的 VO 對象。

      public UserInfoVO originalCopyItem(UserDTO userDTO){ UserInfoVO userInfoVO = new UserInfoVO(); userInfoVO.setUserName(userDTO.getName()); userInfoVO.setAge(userDTO.getAge()); userInfoVO.setBirthday(userDTO.getBirthday()); userInfoVO.setIdCard(userDTO.getIdCard()); userInfoVO.setGender(userDTO.getGender()); userInfoVO.setIsMarried(userDTO.getIsMarried()); userInfoVO.setPhoneNumber(userDTO.getPhoneNumber()); userInfoVO.setAddress(userDTO.getAddress()); return userInfoVO;}

      傳統(tǒng)的方法一般是采用硬編碼,將每個對象的值都逐一設(shè)值。當(dāng)然為了偷懶也會有采用一些 BeanUtil 簡約代碼的方式:

      public UserInfoVO utilCopyItem(UserDTO userDTO){ UserInfoVO userInfoVO = new UserInfoVO(); //采用反射、內(nèi)省機(jī)制實(shí)現(xiàn)拷貝 BeanUtils.copyProperties(userDTO, userInfoVO); return userInfoVO;}

      但是,像 BeanUtils 這類通過反射、內(nèi)省等實(shí)現(xiàn)的框架,在速度上會帶來比較嚴(yán)重的影響。尤其是對于一些大字段、大對象而言,這個速度的缺陷就會越明顯。針對速度這塊我還專門進(jìn)行了測試,對普通的 setter 方法、BeanUtils 的拷貝以及本次需要介紹的 mapperStruct 進(jìn)行了一次對比。得到的耗時結(jié)果如下所示:(具體的運(yùn)行代碼請見附錄)

      運(yùn)行次數(shù)setter方法耗時BeanUtils拷貝耗時MapperStruct拷貝耗時12921528(1)3973292(1.36)2989942(1.023)102362724(1)66402953(28.10)3348099(1.417)1002500452(1)71741323(28.69)2120820(0.848)10003187151(1)157925125(49.55)5456290(1.711)100005722147(1)300814054(52.57)5229080(0.913)10000019324227(1)244625923(12.65)12932441(0.669)

      以上單位均為毫微秒。括號內(nèi)的為當(dāng)前組件同 Setter 比較的比值??梢钥吹?BeanUtils 的拷貝耗時基本為 setter 方法的十倍、二十倍以上。而 MapperStruct 方法拷貝的耗時,則與 setter 方法相近。由此可見,簡單的 BeanUtils 確實(shí)會給服務(wù)的性能帶來很大的壓力。而 MapperStruct 拷貝則可以很好的解決這個問題。

      下面我們就來介紹一下 MapperStruct 這個能夠很好提升我們代碼效率的工具。

      使用教程

      maven依賴

      首先要導(dǎo)入 mapStruct 的 maven 依賴,這里我們選擇最新的版本 1.5.0.RC1。

      … 1.5.0.RC1…//mapStruct maven依賴 org.mapstruct mapstruct ${org.mapstruct.version} … //編譯的組件需要配置 org.apache.maven.plugins maven-compiler-plugin 3.8.1 1.8 1.8 org.mapstruct mapstruct-processor ${org.mapstruct.version}

      在引入 maven 依賴后,我們首先來定義需要轉(zhuǎn)換的 DTO 及 VO 信息,主要包含的信息是名字、年齡、生日、性別等信息。

      @Datapublic class UserDTO { private String name; private int age; private Date birthday; //1-男 0-女 private int gender; private String idCard; private String phoneNumber; private String address; private Boolean isMarried;}@Datapublic class UserInfoVO { private String userName; private int age; private Date birthday; //1-男 0-女 private int gender; private String idCard; private String phoneNumber; private String address; private Boolean isMarried;}

      緊接著需要編寫相應(yīng)的mapper類,以便生成相應(yīng)的編譯類。

      @Mapperpublic interface InfoConverter { InfoConverter INSTANT = Mappers.getMapper(InfoConverter.class); @Mappings({ @Mapping(source = “name”, target = “userName”) }) UserInfoVO convert(UserDTO userDto);}

      需要注意的是,因?yàn)?DTO 中的 name 對應(yīng)的其實(shí)是 VO 中的 userName。因此需要在 converter 中顯式聲明。在編寫完對應(yīng)的文件之后,需要執(zhí)行 maven 的 complie 命令使得 IDE 編譯生成對應(yīng)的 Impl 對象。(自動生成)

      到此,mapperStruct 的接入就算是完成了 。我們就可以在我們的代碼中使用這個拷貝類了。

      public UserInfoVO newCopyItem(UserDTO userDTO, int times) { UserInfoVO userInfoVO = new UserInfoVO(); userInfoVO = InfoConverter.INSTANT.convert(userDTO); return userInfoVO;}

      怎么樣,接入是不是很簡單

      FAQ

      1、接入項(xiàng)目時,發(fā)現(xiàn)并沒有生成對應(yīng)的編譯對象class,這個是什么原因?

      答:可能的原因有如下幾個:

      • 忘記編寫對應(yīng)的 @Mapper 注解,因而沒有生成
      • 沒有配置上述提及的插件 maven-compiler-plugin
      • 沒有執(zhí)行 maven 的 Compile,IDE 沒有進(jìn)行相應(yīng)編譯

      2、接入項(xiàng)目后發(fā)現(xiàn),我項(xiàng)目內(nèi)的 Lombok、@Data 注解不好使了,這怎么辦呢?

      由于 Lombok 本身是對 AST 進(jìn)行修改實(shí)現(xiàn)的,但是 mapStruct 在執(zhí)行的時候并不能檢測到 Lombok 所做的修改,因此需要額外的引入 maven 依賴lombok-mapstruct-binding。

      …… 1.5.0.RC1 0.2.0 1.18.20………… org.mapstruct mapstruct ${org.mapstruct.version} org.projectlombok lombok-mapstruct-binding ${lombok-mapstruct-binding.version} org.projectlombok lombok ${lombok.version}

      更詳細(xì)的,mapperStruct 在官網(wǎng)中還提供了一個實(shí)現(xiàn) Lombok 及 mapStruct 同時并存的案例

      「3、更多問題:」

      歡迎查看MapStruct官網(wǎng)文檔,里面對各種問題都有更詳細(xì)的解釋及解答。

      實(shí)現(xiàn)原理

      在聊到 mapstruct 的實(shí)現(xiàn)原理之前,我們就需要先回憶一下 JAVA 代碼運(yùn)行的過程。大致的執(zhí)行生成的流程如下所示:

      可以直觀的看到,如果我們想不通過編碼的方式對程序進(jìn)行修改增強(qiáng),可以考慮對抽象語法樹進(jìn)行相應(yīng)的修改。而mapstruct 也正是如此做的。具體的執(zhí)行邏輯如下所示:

      為了實(shí)現(xiàn)該方法,mapstruct 基于JSR 269 實(shí)現(xiàn)了代碼。JSR 269 是 JDK 引進(jìn)的一種規(guī)范。有了它,能夠在編譯期處理注解,并且讀取、修改和添加抽象語法樹中的內(nèi)容。JSR 269 使用 Annotation Processor 在編譯期間處理注解,Annotation Processor 相當(dāng)于編譯器的一種插件,因此又稱為插入式注解處理。想要實(shí)現(xiàn) JSR 269,主要有以下幾個步驟:

    1. 繼承 AbstractProcessor 類,并且重寫 process 方法,在 process 方法中實(shí)現(xiàn)自己的注解處理邏輯。
    2. 在 META-INF/services 目錄下創(chuàng)建 javax.annotation.processing.Processor 文件注冊自己實(shí)現(xiàn)的 Annotation Processor。
    3. 通過實(shí)現(xiàn)AbstractProcessor,在程序進(jìn)行 compile 的時候,會對相應(yīng)的 AST 進(jìn)行修改。從而達(dá)到目的。

      public void compile(List sourceFileObjects, List classnames, Iterable processors){ if (processors != null && processors.iterator().hasNext()) explicitAnnotationProcessingRequested = true; // as a JavaCompiler can only be used once, throw an exception if // it has been used before. if (hasBeenUsed) throw new AssertionError(“attempt to reuse JavaCompiler”); hasBeenUsed = true; // forcibly set the equivalent of -Xlint:-options, so that no further // warnings about command line options are generated from this point on options.put(XLINT_CUSTOM.text + “-” + LintCategory.OPTIONS.option, “true”); options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option); start_msec = now(); try { initProcessAnnotations(processors); //此處會調(diào)用到mapStruct中的processor類的方法. delegateCompiler = processAnnotations( enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))), classnames); delegateCompiler.compile2(); delegateCompiler.close(); elapsed_msec = delegateCompiler.elapsed_msec; } catch (Abort ex) { if (devVerbose) ex.printStackTrace(System.err); } finally { if (procEnvImpl != null) procEnvImpl.close(); }}

      關(guān)鍵代碼,在mapstruct-processor包中,有個對應(yīng)的類MappingProcessor繼承了 AbstractProcessor,并實(shí)現(xiàn)其 process 方法。通過對 AST 進(jìn)行相應(yīng)的代碼增強(qiáng),從而實(shí)現(xiàn)對最終編譯的對象進(jìn)行修改的方法。

      @SupportedAnnotationTypes({“org.mapstruct.Mapper”})@SupportedOptions({“mapstruct.suppressGeneratorTimestamp”, “mapstruct.suppressGeneratorVersionInfoComment”, “mapstruct.unmappedTargetPolicy”, “mapstruct.unmappedSourcePolicy”, “mapstruct.defaultComponentModel”, “mapstruct.defaultInjectionStrategy”, “mapstruct.disableBuilders”, “mapstruct.verbose”})public class MappingProcessor extends AbstractProcessor { public boolean process(Set annotations, RoundEnvironment roundEnvironment) { if (!roundEnvironment.processingOver()) { RoundContext roundContext = new RoundContext(this.annotationProcessorContext); Set deferredMappers = this.getAndResetDeferredMappers(); this.processMapperElements(deferredMappers, roundContext); Set mappers = this.getMappers(annotations, roundEnvironment); this.processMapperElements(mappers, roundContext); } else if (!this.deferredMappers.isEmpty()) { Iterator var8 = this.deferredMappers.iterator(); while(var8.hasNext()) { MappingProcessor.DeferredMapper deferredMapper = (MappingProcessor.DeferredMapper)var8.next(); TypeElement deferredMapperElement = deferredMapper.deferredMapperElement; Element erroneousElement = deferredMapper.erroneousElement; String erroneousElementName; if (erroneousElement instanceof QualifiedNameable) { erroneousElementName = ((QualifiedNameable)erroneousElement).getQualifiedName().toString(); } else { erroneousElementName = erroneousElement != null ? erroneousElement.getSimpleName().toString() : null; } deferredMapperElement = this.annotationProcessorContext.getElementUtils().getTypeElement(deferredMapperElement.getQualifiedName()); this.processingEnv.getMessager().printMessage(Kind.ERROR, “No implementation was created for ” + deferredMapperElement.getSimpleName() + ” due to having a problem in the erroneous element ” + erroneousElementName + “. Hint: this often means that some other annotation processor was supposed to process the erroneous element. You can also enable MapStruct verbose mode by setting -Amapstruct.verbose=true as a compilation argument.”, deferredMapperElement); } } return false; }}

      「如何斷點(diǎn)調(diào)試:」

      因?yàn)檫@個注解處理器是在解析->編譯的過程完成,跟普通的 jar 包調(diào)試不太一樣,maven 框架為我們提供了調(diào)試入口,需要借助 maven 才能實(shí)現(xiàn) debug。所以需要在編譯過程打開 debug 才可調(diào)試。

      • 在項(xiàng)目的 pom 文件所在目錄執(zhí)行 mvnDebug compile
      • 接著用 idea 打開項(xiàng)目,添加一個 remote,端口為 8000
      • 打上斷點(diǎn),debug 運(yùn)行 remote 即可調(diào)試。

      附錄

      測試代碼如下,采用Spock框架 + JAVA代碼實(shí)現(xiàn)。Spock框架作為當(dāng)前最火熱的測試框架,你值得學(xué)習(xí)一下。Spock框架初體驗(yàn):更優(yōu)雅地寫好你的單元測試

      // @Resource @Shared MapperStructService mapperStructService def setupSpec() { mapperStructService = new MapperStructService() } @Unroll def “test mapperStructTest times = #times”() { given: “初始化數(shù)據(jù)” UserDTO dto = new UserDTO(name: “笑傲菌”, age: 20, idCard: “1234”, phoneNumber: “18211932334”, address: “北京天安門”, gender: 1, birthday: new Date(), isMarried: false) when: “調(diào)用方法”// 傳統(tǒng)的getter、setter拷貝 long startTime = System.nanoTime(); UserInfoVO oldRes = mapperStructService.originalCopyItem(dto, times) Duration originalWasteTime = Duration.ofNanos(System.nanoTime() – startTime);// 采用工具實(shí)現(xiàn)反射類的拷貝 long startTime1 = System.nanoTime(); UserInfoVO utilRes = mapperStructService.utilCopyItem(dto, times) Duration utilWasteTime = Duration.ofNanos(System.nanoTime() – startTime1); long startTime2 = System.nanoTime(); UserInfoVO mapStructRes = mapperStructService.newCopyItem(dto, times) Duration mapStructWasteTime = Duration.ofNanos(System.nanoTime() – startTime2); then: “校驗(yàn)數(shù)據(jù)” println(“times = “+ times) println(“原始拷貝的消耗時間為: ” + originalWasteTime.getNano()) println(“BeanUtils拷貝的消耗時間為: ” + utilWasteTime.getNano()) println(“mapStruct拷貝的消耗時間為: ” + mapStructWasteTime.getNano()) println() where: “比較不同次數(shù)調(diào)用的耗時” times || ignore 1 || null 10 || null 100 || null 1000 || null }

      測試的Service如下所示:

      public class MapperStructService { public UserInfoVO newCopyItem(UserDTO userDTO, int times) { UserInfoVO userInfoVO = new UserInfoVO(); for (int i = 0; i < times; i++) { userInfoVO = InfoConverter.INSTANT.convert(userDTO); } return userInfoVO; } public UserInfoVO originalCopyItem(UserDTO userDTO, int times) { UserInfoVO userInfoVO = new UserInfoVO(); for (int i = 0; i < times; i++) { userInfoVO.setUserName(userDTO.getName()); userInfoVO.setAge(userDTO.getAge()); userInfoVO.setBirthday(userDTO.getBirthday()); userInfoVO.setIdCard(userDTO.getIdCard()); userInfoVO.setGender(userDTO.getGender()); userInfoVO.setIsMarried(userDTO.getIsMarried()); userInfoVO.setPhoneNumber(userDTO.getPhoneNumber()); userInfoVO.setAddress(userDTO.getAddress()); } return userInfoVO; } public UserInfoVO utilCopyItem(UserDTO userDTO, int times) { UserInfoVO userInfoVO = new UserInfoVO(); for (int i = 0; i < times; i++) { BeanUtils.copyProperties(userDTO, userInfoVO); } return userInfoVO; }}

      鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權(quán)歸原作者所有,如有侵權(quán)請聯(lián)系管理員(admin#wlmqw.com)刪除。
      用戶投稿
      上一篇 2022年6月18日 21:24
      下一篇 2022年6月18日 21:24

      相關(guān)推薦

      • 分享4條發(fā)微商朋友圈的方法(微商朋友圈應(yīng)該怎么發(fā))

        對于微商朋友來說,朋友圈的重要性不言而喻了。 那么微商的朋友圈到底該怎么發(fā)呢? 為什么同樣是經(jīng)營一個朋友圈,有的微商看起來逼格滿滿,實(shí)際效果也不錯;而有的卻動都不動就被屏蔽甚至拉黑…

        2022年11月27日
      • 30個無加盟費(fèi)的項(xiàng)目(茶顏悅色奶茶店加盟費(fèi)多少)

        茶顏悅色又爆了,8月18日,茶顏悅色南京門店正式開業(yè),開張不到半小時,門店就人滿為患,消費(fèi)者的購買熱情十分高漲,而由于人流量過大造成擁堵,茶顏悅色也不得不暫停營業(yè)。 當(dāng)然,這里面排…

        2022年11月27日
      • 短視頻策劃內(nèi)容的3個要點(diǎn)(短視頻策劃內(nèi)容怎么做)

        短視頻在制作時,內(nèi)容框架非常重要。如果直奔主題,然后結(jié)束,聚卓告訴你,這樣的短視頻已經(jīng)過時了?,F(xiàn)在的短視頻需要框架的,但不是任何框架,它需要一種易于理解和消化的框架。而且,現(xiàn)在大多…

        2022年11月27日
      • 凈利潤率越高越好嗎(凈利潤率多少合適)

        一、持續(xù)增收不增利,平均凈利潤率首次跌入個位數(shù) 2021年,增收不增利依舊是行業(yè)主流。具體來看,大部分企業(yè)營業(yè)收入呈增長態(tài)勢,E50企業(yè)平均同比增速達(dá)到17.3%,但是利潤增速則明…

        2022年11月26日
      • 《寶可夢朱紫》夢特性怎么獲得?隱藏特性獲取方法推薦

        寶可夢朱紫里有很多寶可夢都是擁有夢特性會變強(qiáng)的寶可夢,很多玩家不知道夢特性怎么獲得,下面就給大家?guī)韺毧蓧糁熳想[藏特性獲取方法推薦,感興趣的小伙伴一起來看看吧,希望能幫助到大家。 …

        2022年11月25日
      • 《寶可夢朱紫》奇魯莉安怎么進(jìn)化?奇魯莉安進(jìn)化方法分享

        寶可夢朱紫中的奇魯莉安要怎么進(jìn)化呢?很多玩家都不知道,下面就給大家?guī)韺毧蓧糁熳掀骠斃虬策M(jìn)化方法分享,感興趣的小伙伴一起來看看吧,希望能幫助到大家。 奇魯莉安進(jìn)化方法分享 奇魯莉安…

        2022年11月25日
      • 寶可夢朱紫野怪對應(yīng)努力值表 野怪對應(yīng)努力值查詢一覽圖

        寶可夢朱紫野怪對應(yīng)努力值是多少?不同的野怪對應(yīng)的努力值不一樣,因此不少玩家對于野怪對應(yīng)努力值的詳情不太了解,今天我們就來看一看野怪對應(yīng)努力值表的具體內(nèi)容,小編已經(jīng)將詳情分享在下面,…

        2022年11月25日
      • 規(guī)范透明促PPP高質(zhì)量發(fā)展——16萬億元大市場迎來新規(guī)

        近日,財政部印發(fā)《關(guān)于進(jìn)一步推動政府和社會資本合作(PPP)規(guī)范發(fā)展、陽光運(yùn)行的通知》,從做好項(xiàng)目前期論證、推動項(xiàng)目規(guī)范運(yùn)作、嚴(yán)防隱性債務(wù)風(fēng)險、保障項(xiàng)目陽光運(yùn)行四個方面進(jìn)一步規(guī)范P…

        2022年11月25日
      • 推薦3種白手起家的賺錢項(xiàng)目(白手起家賺錢項(xiàng)目有哪些)

        如今社會壓力非常的大,家有老少要養(yǎng)活,這些都加速了窮人想要創(chuàng)業(yè)的欲望,但是創(chuàng)業(yè)路總是那么的艱難,資金就是創(chuàng)業(yè)的重頭戲,所以選擇一個低成本又賺錢的項(xiàng)目是大多數(shù)人最期望的了,那么有哪些…

        2022年11月25日
      • 閑魚運(yùn)營的4大技巧解析(閑魚運(yùn)營怎么做)

        熟悉我又來了,上一次寫的文章是爆出風(fēng)水項(xiàng)目的潛規(guī)則,但那個項(xiàng)目已經(jīng)涼涼了。 這一次我是要教一些小白,你們第一次做互聯(lián)網(wǎng)的建議做的項(xiàng)目之一,這個項(xiàng)目就是閑魚賣二手物品賺差價了!!! …

        2022年11月24日

      聯(lián)系我們

      聯(lián)系郵箱:admin#wlmqw.com
      工作時間:周一至周五,10:30-18:30,節(jié)假日休息