A comprehensive and very practical introduction to many useful usecases of Project Lombok on standard Java code.
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.AvoidRepetitiveCode
Javaisagreatlanguage,butitcansometimesgettooverboseforcommontaskswehavetodoinourcodeorcompliancewithsomeframeworkpractices.Thisoftendoesn'tbringanyrealvaluetothebusinesssideofourprograms,andthat'swhereLombokcomesintomakeusmoreproductive.
Thewayitworksisbypluggingintoourbuildprocessandauto-generatingJavabytecodeintoour.classfilesasperanumberofprojectannotationsweintroduceinourcode.
Furtherreading:LombokBuilderwithDefaultValueLearnhowtocreateabuilderdefaultpropertyvaluesusingLombokReadmore→SettingupLombokwithEclipseandIntellijLearnhowtosetupLombokwithpopularIDEsReadmore→
Includingitinourbuilds,inwhicheversystemwe'reusing,isverystraightforward.ProjectLombok'sprojectpagehasdetailedinstructionsonthespecifics.Mostofmyprojectsaremavenbased,soIjusttypicallydroptheirdependencyintheprovidedscopeandI'mgoodtogo:
...
org.projectlombok
lombok
1.18.20
provided
...
Wecancheckforthemostrecentavailableversionhere.
NotethatdependingonLombokwon'tmakeusersofour.jarsdependonitaswell,asitisapurebuilddependency,notruntime.
2.Getters/Setters,Constructors–SoRepetitive
EncapsulatingobjectpropertiesviapublicgetterandsettermethodsissuchacommonpracticeintheJavaworld,andlotsofframeworksrelyonthis“JavaBean”patternextensively(aclasswithanemptyconstructorandget/setmethodsfor“properties”).
ThisissocommonthatmostIDE'ssupportauto-generatingcodeforthesepatterns(andmore).However,thiscodeneedstoliveinoursourcesandbemaintainedwhenanewpropertyisaddedorafieldrenamed.
Let'sconsiderthisclasswewanttouseasaJPAentity:
@Entity
publicclassUserimplementsSerializable{
private@IdLongid;//willbesetwhenpersisting
privateStringfirstName;
privateStringlastName;
privateintage;
publicUser(){
}
publicUser(StringfirstName,StringlastName,intage){
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
//gettersandsetters:~30extralinesofcode
}
Thisisarathersimpleclass,butimagineifwehadaddedtheextracodeforgettersandsetters.Wewouldhaveendedupwithadefinitionwheretherewouldbemoreboilerplatezero-valuecodethantherelevantbusinessinformation:“aUserhasfirstandlastnames,andage.”
Let'snowLombok-izethisclass:
@Entity
@Getter@Setter@NoArgsConstructor//transactions=getTransactions();
privateMapgetTransactions(){
finalMapcache=newHashMap<>();
ListtxnRows=readTxnListFromFile();
txnRows.forEach(s->{
String[]txnIdValueTuple=s.split(DELIMETER);
cache.put(txnIdValueTuple[0],Long.parseLong(txnIdValueTuple[1]));
});
returncache;
}
}
ThisreadssometransactionsfromafileintoaMap.Sincethedatainthefiledoesn'tchange,we'llcacheitonceandallowaccessviaagetter.
Ifwenowlookatthecompiledcodeofthisclass,we'llseeagettermethodwhichupdatesthecacheifitwasnullandthenreturnsthecacheddata:
publicclassGetterLazy{
privatefinalAtomicReference