Guide to Lombok With Spring Boot - Better Programming

文章推薦指數: 80 %
投票人數:10人

Imagine you saw a bunch of boilerplate codes in a newly created app and you need to clean it up. If you are aware of Lombok, ... OpeninappHomeNotificationsListsStoriesWritePublishedinBetterProgrammingGuidetoLombokWithSpringBootTop5mostfrequentlyusedAnnotationsandHiddenissuesImagedesignedbyYasasSandeepa(TheAuthor)Imagineyousawabunchofboilerplatecodesinanewlycreatedappandyouneedtocleanitup.IfyouareawareofLombok,youwilldefinitelytrythatout.Butbeware!Youmaynotknowwhattheconsequencesareofusingthat!Sotoday,IintendtobringyouthemostimportantandwidelyusedannotationsinLombokwiththeirlimitations.ThiswillgiveyouaclearunderstandingofhowtouseLombokinyourproject.ForthosewhoarenotfamiliarwithprojectLombok,I’llintroduceitveryshortly.WhatIsLombok?Aspertheofficialdocs,“ProjectLombokisajavalibrarythatautomaticallyplugsintoyoureditorandbuildtools,spicingupyourJava.”Itisbasicallyanannotationprocessorthatworksatcompile-timetoaddcodeintoyourclasses.WhyLombok?ThemainadvantageofLombokisitminimizes/removestheboilerplatecodeandsavestheprecioustimeofdevelopersduringdevelopment.Inthebestcases,itcanreplacehundredsoflinesofcodetoonlyfivelines.Itincreasesthereadabilityofthesourcecode(cleancoding)andsavesspacebyreducinglinesofcode.Also,itcaneliminatethemisleadingloggingissuesinyourapplication.HowtoinstallLomboksupportsallthemajorIDEs,suchasIntelliJ,Eclipse,Netbeans,andeveninVScode.HereI’musingIntelliJasitisthemostwidelyusedIDEforJava.IfyouwanttoknowhowtosetupadifferentIDE,readtheofficialdocumentationhere.AsofIntelliJversion2020.3,youdon’tneedtoconfiguretheIDEtouseLombokanymore.Butfortheolderversion,youneedtohavetheIntelliJLombokplugin.LombokPlugininIntelliJ(ImagebyAuthor)Youalsoneedtoenableannotationprocessing.InIntelliJ,gotoFile->Settings->Build,Execution,Deployment->Compiler->AnnotationProcessors.SelecttheEnableannotationprocessingcheckbox.Enableannotationprocessing(ImagebyAuthor)Ifyouareusingitwithaspringbootproject,youneedtoaddthismavendependencyintotheproject'spomfileaswell.Allright!Let’sseewhatthemostusedannotationsareinLombok.1.@Getterand@SetterWhenyouneedanencapsulation,youobviouslygoforgettersandsetters.Butyouknowhowmanyboilerplatecodesareneededforeachfield.Lombokresolvesthisproblem.Ifyouwanttogenerategettersandsetters,youjusthavetoannotatetheclasswith@[email protected](VanillaJava):WithLombok:SeehowLombokreducedtheboilerplatecode.Furthermore,youcanaddthegettersandsettersonebyonetoeachvariableasperyourwish.LombokalsointroducedaLazygetterthatcanbeusedtocachethedataonceandallowaccessviaagetter.Itwillretrievethedataonce,andthencachethedatatoallowin-memoryreadswithintheapplication.@Getter(lazy=true)privatefinalMaptransactions=getTransactions();ButthereisaknownissueinLombokwhengeneratinggettersandsetters.Lombokgeneratesthewronggettersandsettersforvariable/attributesthatarenamedasfirstcharlowercaseandnextcharuppercase.SupposethereisaninstancevariablepCodeNoinyourclass.Sothegettersandsetterswillbeasfollowsifwegeneratethemmanually.Note:Thisisthecorrectway!ButwithLombok,itwillcapitalizethefirstletteraswell.Itgeneratesasfollows:Althoughitisthenormalbehaviour,itisincorrectandcouldbeproblematicwhenyoudefineanAPIusingSpringBoot.Furthermore,thereisnobenefitofusingannotatedgettersandsettersinclasseswithbusinesslogic.SouseLombokwisely,accordingtoyourrequirements.2.@NoArgsConstructorand@AllArgsConstructorConstructorisaspecialmethodthatisusedtoinitializeobjects.Lombokprovidesthreeannotationstocreateaconstructor,buttwoofthemarepopularones.@NoArgsConstructorgeneratesadefaultconstructorwithnoparameters.@AllArgsConstructorgeneratesaconstructorrequiringanargumentforeveryfieldintheannotatedclass.Butifyouneedacustomparameterizedconstructor,youneedtowriteitexplicitly.Also,Lombokprovidesa@RequiredArgsConstructorthatgeneratesaconstructorwithrequiredarguments.Requiredargumentsarefinalfieldsandfieldswithconstraintssuchasnotnull.WithoutLombok:WithLombok:So,asyoucansee,wecanwritethesameclassusingLombokwithfewercodes.Also,youdonotneedtogeneratenewgettersandsettersfornewlycreatedfields.Buthere’sthedrawback:itdoesnotprovideanycodeviolationerrors.Asgooddevelopers,wealwaysneedtoensureourcodeisinastandardformat.YoucanuseanalyticstoolssuchasCheckstyle,Sonar,etc.,tocheckifJavasourcecodeiscompliantwithspecifiedcodingrulesandcontinuousinspectionofcodequality.SeethebelowEmployeeclassasanexample.TheCheckstyletoolgivestheanalysis,anditshowstheerrorsandwarnings.CheckstyleerrorsinvanillaJavaclass(ImagebyAuthor)ButtheLombokannotationshidethoseerrorsandwarnings.CheckstyleerrorsinLombokannotatedclass(ImagebyAuthor)SoyouneedtomakesureyourcodeisaccordingtothestandardbeforeaddingLombok.DonothideCheckstyleorSonarviolationsratherthanfixingthem.That’swhyyoushouldnotaddLombokannotationsintotheclassesbeforeimplementinganything.3.@ToStringThetoString()methodisusedtoreturnastringrepresentationofanobject.Bydefault,itreturnsastringconsistingofthenameoftheclassfollowedby@signandthenanunsignedhexadecimalrepresentationofthehashcodeoftheobject.So,weneedtooverridethetoString()methodtoprinttheactualvaluesofobjects.WithoutLombok(VanillatoString()methodgeneratedbyIntelliJ):WithLombok:@ToStringmethodwithandwithoutLombok(ImagebyAuthor)Bothprovidesimilaroutputs,butLombokreducedtheboilerplatecode.Lesscode,lesscomplexity!Butthereisanissuewithusingthisannotationforsomescenarios.I’llexplainitafterthebelowDataannotation.4.@DataThisannotationisanall-in-onespecialannotationthatbundlesthefeaturesof@RequiredArgsConstructor,@Getter,@Setter,@ToStringand@EqualsAndHashCodeannotationsintoasingleannotation.Itgeneratesgettersforallfields,settersforallnon-finalfields,aconstructorthatinitializesallthefinalfields,andappropriatetoString,equalsandhashCodemethods.WithoutLombok:WithLombok:Seehowmanylinesofcodehavebeenreduced!Thereisadrawbackthatsometimeswereallydon’tusethesemethods.Asanexample,wemaynotneedtheequalsandthehashcodeimplementations.Asabestpractice,ourcodebaseshouldnothaveanythingthatwedonotuse.Whateverthecodeswewritemusthaveareasontoexist.Ifnot,weshouldremovethem.Sodon’taddthisannotationblindlyifyouarenotusingmostofthemethods.Youcanusetheannotationsseparatelybydisassemblingthe@Dataannotation.Furthermore,LombokcanintroduceafewdangerouspitfallswhenyouuseitwithJPA.MisuseofLombokcanimpacttheperformanceofJPAapplicationsorevencrashthem.IntelliJJPABuddypluginalertsdeveloperswiththiswarning(ImagebyAuthor)ThiswarningcomesbecauseofthehashCode()implementationastherearenofieldswecanrelyontocalculatethehashCode.CallinghashCode()onalazy@OneToManymayfetchalltheentitiesitcontains.Thiscaneasilyimpacttheapplication'sperformance.Thisisalsovalidforthepreviouslymentioned@ToStringannotation.IntelliJJPABuddypluginalerts(ImagebyAuthor)Byexcludingallthelazyfields,@ToStringannotationcanstillbeused.ButIrecommendyouavoidusing@Data,@EqualsAndHashCodeand@ToStringannotationsinJPAentitiesasyoudonotneedtoaccidentallyimpacttheperformanceofyourapplication.5.Loggingwithsl4j—@sl4jLoggingisanimportantpartofdevelopmentthatrecordstheeventsthatthesystemisperformingatanygivenpointintime.Youneedtowritelogsproperlyinordertorecognizetheissuesandtoseeifeverythingisworkingasexpected.Butsettinguploggingisquitecumbersomeasweneedtodefinetheloggereverytimeintheclasstoaccessthelogger.Loggerlog=LoggerFactory.getLogger(Example.class)Inmostcases,developerswouldcopyandpastethecodefromoneclasstoanother.Butsometimestheyforgettochangetheclassname,resultinginmisleadinglogs.Lombokprovidesabettersolutiontothat.Youcanusethe@Sl4jannotationtogetridoftheboilerplatecode.Also,LomboksupportsotherloggingframeworkssuchasLog,Log4j,@JBossLog,@Flogger,etc.Ihopeyouareawareofthelog4jzero-dayvulnerabilityissuethatwasexposedrecently.Soyoushouldbemorecarefulusingtheseloggers.WithoutLombok:WithLombok:Lookhoweasythatis.Youonlyneedtoaddtheannotation.Sl4jAnnotation(ImagebyAuthor)Therearemoreannotationslike@Builderthatareusedwhenimplementingthebuilderpattern.Butpersonally,Iwouldsuggestnottouseitbecauseitisverydifficulttorefactor.Also,becarefulwith@UtilityClassannotationasitdoesn’tworkwithstaticimports.Becausestaticimportsareresolvedbeforetheannotationprocessorsarerun.Youcanalwaysde-Lombokthecodetochecktheannotationsaregivingtheexpectedoutcome.ExaminetheLombok-generatedcodeinsidethetargetfolderafteryouruntheapplication.De-Lombokedcodeinthetargetfolder(ImagebyAuthor)ResourcesOfficialLombokdocumentation—ProjectLombok.ThesourcecodefortheexamplesisavailableoveronGitHub.ConclusionLombokisaphenomenalprojectsupportedbyalargecommunityanddoesagreatjobofreducingtheboilerplatecodeofexistingimplementations.Butsuchpowercomeswithgreatresponsibility.Youhavetolearnitfirstbeforeaddingtheannotations.SomyadviceistowritethevanillaJavacodefirst.Itwillgiveyouaclearunderstandingofthebigpicture.ThencheckanyviolationsfromSonaroranyothertools.Ifallthethingsaregoodtogo,youcanaddtheLomboktoreducetheboilerplatecode.Don’tjustadditblindly,butuseitintelligently.Betterprogrammingformakingtheworldabetterplace!Thanksforreading.Ihopethiswashelpful.Ifyouhavequestionsorfeedback,feelfreetoleavearesponse.Happycoding!👨‍💻❤️MorefromBetterProgrammingFollowAdviceforprogrammers.Here’swhyyoushouldsubscribe:https://bit.ly/bp-subscribeReadmorefromBetterProgrammingMorefromMediumHowBuildingDronesMadeMeABetterEngineer!ProgrammingLanguagesWiththeHighestAmountofJobListings(Indeed,Glassdoor,LinkedIn,and…Hackingforfun:amaker’ssuperpowerOpinion:Hacking,justforfun,isthe#1healthiestthingamakercando.HowtoaccessMLSdatafromtheRealEstateBoardofGreaterVancouver(REBGV)DrinkingYourOwnChampagne:PerformanceDebuggingasExploratoryVisualAnalysisFixingHibernateN+1probleminSpringBootApplicationWhyUseATerraformTemplate?Thepastfewmonths,we’vecoveredvariousTerraformandDevOpsconceptsthroughourblogs.PythonAbstractBaseClassesforContainersandContainerDataTypesGetstartedYasasSandeepa824FollowersAnenergetichighlymotivatedTechEnthusiastic.FollowingBachelorofScience(Hons)inInformationTechnology|UniversityofMoratuwa✨https://yasas.live✨FollowRelatedEvolvingyourRESTfulAPIs,astep-by-stepapproach2WaystoUploadFilestoAmazonS3InYourSpringBootProjectToned-downCodeComplexityUsingFacadeDesignPatternAuto-configurationwithSpringBootSpringBootismuchmorethananapplicationgenerator.Itisatoolthatallowsyoutodohyperprogramming;therefore,avoidwriting…HelpStatusWritersBlogCareersPrivacyTermsAboutKnowable



請為這篇文章評分?