Omitting Getter or Setter in Lombok | Baeldung

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

This access level lets us override the behavior of a @Getter, @Setter, or @Data annotation on a class. To override the access level, annotate ... StartHereCourses ▼▲ RESTwithSpring(30%off) ThecanonicalreferenceforbuildingaproductiongradeAPIwithSpring LearnSpringSecurity(30%off) ▼▲ THEuniqueSpringSecurityeducationifyou’reworkingwithJavatoday LearnSpringSecurityCore(30%off) FocusontheCoreofSpringSecurity5 LearnSpringSecurityOAuth(30%off) FocusonthenewOAuth2stackinSpringSecurity5 LearnSpring(30%off) Fromnoexperiencetoactuallybuildingstuff​ LearnSpringDataJPA(30%off) ThefullguidetopersistencewithSpringDataJPA Guides ▼▲ Persistence ThePersistencewithSpringguides REST TheguidesonbuildingRESTAPIswithSpring Security TheSpringSecurityguides About ▼▲ FullArchive Thehighleveloverviewofallthearticlesonthesite. BaeldungEbooks DiscoverallofoureBooks AboutBaeldung AboutBaeldung. MarchDiscountLaunch2022 We’refinallyrunningaspringlaunch.AllCoursesare30%offuntilnextFriday: >>GETACCESSNOW 1.Overview Sometimes,wewanttohidetheabilitytogetorsetafieldvalueinourobjects.ButLombokgeneratesthedefaultgetter/setterautomatically.Inthisquicktutorial,we'llshowhowwecanomitthegettersandsettersfrombeinggeneratedbyLombok.AdetailedlookattheProjectLomboklibraryisalsoavailableinIntroductiontoProjectLombok. Beforecontinuing,weshouldinstalltheLombokplugininourIDE. 2.Dependencies First,weneedtoaddLomboktoourpom.xmlfile: org.projectlombok lombok 1.18.22 provided 3.DefaultBehavior Beforewegetintothedetailsofhowtoomitthegenerationofgettersandsetters,let'sreviewthedefaultbehavioroftheannotationsresponsibleforgeneratingthem. 3.1.@Getterand@SetterAnnotations Lombokprovidestwoaccessorannotations,@Getterand@Setter.Wecanannotateeveryfieldorsimplymarkthewholeclasswiththem.Generatedmethodswillbepublicbydefault.However,wecanchangetheaccessleveltoprotected,package,orprivate.Let'sseeanexample: @Setter @Getter publicclassUser{ privatelongid; privateStringlogin; privateintage; } WecanusethedelombokoptionfromtheplugininourIDEandseethecodeLombokgenerated: publicclassUser{ privatelongid; privateStringlogin; privateintage; publiclonggetId(){ returnthis.id; } publicStringgetLogin(){ returnthis.login; } publicintgetAge(){ returnthis.age; } publicvoidsetId(longid){ this.id=id; } publicvoidsetLogin(Stringlogin){ this.login=login; } publicvoidsetAge(intage){ this.age=age; } } Aswecanobserve,allgettersandsetterswerecreated.Getterandsettersforallfieldsarepublicbecausewedidn'tspecifytheaccesslevelonanyfieldexplicitly. 3.2.@Data Annotation @Datacombinesfeaturesofafewotherannotations,includingboth@[email protected],inthiscase,defaultaccessormethodswillbegeneratedaspublicalso: @Data publicclassEmployee{ privateStringname; privateStringworkplace; privateintworkLength; } 4.OmittingGetterorSetterUsingAccessLevel.NONE  Todisabledefaultgetter/settergenerationonaspecificfield,weshoulduseaspecificaccesslevel: @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) Thisaccesslevelletsusoverridethebehaviorofa@Getter,@Setter,[email protected],annotatethefieldorclasswithanexplicit@Setteror@Getterannotation. 4.1.Overriding@Getterand@SetterAnnotations Let'schangetheAccessLeveltoNONEonthegetterfortheagefieldandthesetterfortheidfield: @Getter @Setter publicclassUser{ @Setter(AccessLevel.NONE) privatelongid; privateStringlogin; @Getter(AccessLevel.NONE) privateintage; } Let'sdelombokthiscode: publicclassUser{ privatelongid; privateStringlogin; privateintage; publiclonggetId(){ returnthis.id; } publicStringgetLogin(){ returnthis.login; } publicvoidsetLogin(Stringlogin){ this.login=login; } publicvoidsetAge(intage){ this.age=age; } } Aswecansee,there'snosetterfortheid fieldandgogetterfortheagefield. 4.2.Overridingthe@DataAnnotation Let'sseeanotherexample,inwhichwechangetheAccessLeveltoNONEontheclasswiththe@Dataannotation: @Data publicclassEmployee{ @Setter(AccessLevel.NONE) privateStringname; privateStringworkplace; @Getter(AccessLevel.NONE) privateintworkLength; } Weaddedtheexplicit@GetterannotationtotheworkLengthfieldandexplicit@Setterannotationtothenamefield.TheAccessLevelofbothaccessorsissettoNONE.Let'sseethedelombokcode: publicclassEmployee{ privateStringname; privateStringworkplace; privateintworkLength; publicStringgetName(){ returnthis.name; } publicStringgetWorkplace(){ returnthis.workplace; } publicvoidsetWorkplace(Stringworkplace){ this.workplace=workplace; } publicvoidsetWorkLength(intworkLength){ this.workLength=workLength; } } Asweexpected,ourexplicitsettingsof@Getterand@Setteroverridethegettersandsettersgeneratedbythe@Dataannotation.ThereisnosettergeneratedforthenamefieldandnogettergeneratedfortheworkLengthfield. 5.Conclusion Inthisarticle,weexploredhowtoomitgetterandsettergenerationbyLombokforspecificfieldsinourobjects.Moreover,wesawexamplesfor@Getter,@Setter,[email protected],wesawthecodethatLombokgeneratedforourannotationsettings. Asalways,thecodeisavailable overonGitHub. MarchDiscountLaunch2022 We’refinallyrunningaspringlaunch.AllCoursesare30%offuntilnextFriday: >>GETACCESSNOW Genericfooterbanner LearningtobuildyourAPIwithSpring? DownloadtheE-book Commentsareclosedonthisarticle! LaunchDiscount30% OnAllCourses VIEWDETAILS Followthe Java Category FollowtheJavacategorytogetregularinfoaboutthenewarticlesandtutorialswepublishhere. FOLLOWTHEJAVACATEGORY



請為這篇文章評分?