Project Lombok is a mature library that reduces boilerplate code. In this tutorial we will walk through a simple Lombok Spring Boot example ...
JavaNews
CoreJava
JUnit5
ORM
JPAwithHibernate
Lombok
ContactUs
Search
javabydeveloperJavaTutorials
Signin
Welcome!Logintoyouraccount
yourusername
yourpassword
Forgotyourpassword?Gethelp
PrivacyPolicy
Passwordrecovery
Recoveryourpassword
youremail
Apasswordwillbee-mailedtoyou.
javabydeveloperJavaTutorials
JavaNews
CoreJava
JUnit5
ORM
JPAwithHibernate
Lombok
ContactUs
Search
Signin/Join
Facebook
Twitter
Pinterest
WhatsApp
Linkedin
Email
Telegram
reportthisad
HomeLombokLombok+SpringBootExample
Lombok+SpringBootExample
BySatishVarma
May18,2020
ProjectLombok isamaturelibrarythatreducesboilerplatecode.InthistutorialwewillwalkthroughasimpleLombokSpringBootexampleapplicationthatintegrateswithLomboktodemonstratehowtostartworkingwithSpringBootandLomboktogether.
1.MavendependenciesforSpringBootandLombok
FollowingdependenciesareusedtoworkwithSpringBootandLombokandfortestingSpringcomponents.MakesureyoualreadyinstalledlomboksetupforyourIDE.ToSetupinEclipseorinSpringToolSuiterefertoourLombokMavenexamplesetupwithEclipse.
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-test
test
org.junit.jupiter
junit-jupiter-engine
${junit.jupiter.version}
test
2.ProjectStructure
2.SpringComponents+Lombok
2.1.MessageDtoclassannotatedwithLombok’[email protected] @Data causesLomboktogenerategettersandsettersforeachofthenonstaticclassfieldsandaclassconstructor,aswellasthe toString(), equals(),and hashCode() methods.Italsocreatesaconstructorthatacceptsanyfinalfieldsorthoseannotatedwith @NonNull asarguments.
Lombok@DataisequivalenttocombinationofLombok’s@Getter+@Setter+@RequiredArgsConstructor+@ToString+@EqualsAndHashCode
@Data//lombokdataannotation
publicclassMessageDto{
privateLongid;
privateStringmessage;
}
2.2.UsingMessageDtoinMessageService.
@Component
publicclassMessageService{
publicMessageDtogetSubscriptionMessage(@NonNullStringuser){
MessageDtomessage=newMessageDto();
message.setId(Long.valueOf(1));
message.setMessage("Hello"+user+",Thanksforthesubscription!");
returnmessage;
}
}
2.3.CreatinglogmessagesusingLombokinSpringController.
UsedLombok@Slf4jfrologging.
@Slf4j//lombok
@RestController
publicclassHelloController{
@Autowired
privateMessageServicemessageService;
@GetMapping("/hello")
publicMessageDtosayHello(@RequestParamStringuser){
log.info("testinfolog:"+user);
MessageDtomessage=messageService.getSubscriptionMessage(user);
log.debug("testdebuglog:"+message.toString());
returnmessage;
}
}
2.4.TestingSpringController
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
publicclassSpring_boot_junit5_api_test{
@Autowired
privateTestRestTemplaterestTemplate;
@Test
@DisplayName("/hellorestapitest")
voidtestMessage(){
Stringuser="Peter";
URItargetUrl=UriComponentsBuilder.fromUriString("/hello")
.queryParam("user",user)
.build()
.encode()
.toUri();
MessageDtomessage=this.restTemplate.getForObject(targetUrl,MessageDto.class);
assertEquals("Hello"+user+",Thanksforthesubscription!",message.getMessage());
}
}
2.5.ChecklogmessagesinOutputResults
Testresultswerepassedandfollowingisconsoleoutputandloginfo.
._________
/\\/___'_____(_)______\\\\
(()\___|'_|'_||'_\/_`|\\\\
\\/___)||_)|||||||(_||))))
'|____|.__|_||_|_||_\__,|////
=========|_|==============|___/=/_/_/_/
::SpringBoot::(v2.2.2.RELEASE)
20:34:11.322[main]INFOc.j.demo.Spring_boot_junit5_api_test-StartingSpring_boot_junit5_api_testonADMINA565withPID12988(startedbyadminin\Workspaces\Lombok\spring-boot-lombok-example)
20:34:11.333[main]DEBUGc.j.demo.Spring_boot_junit5_api_test-RunningwithSpringBootv2.2.2.RELEASE,Springv5.2.2.RELEASE
20:34:11.335[main]INFOc.j.demo.Spring_boot_junit5_api_test-Noactiveprofileset,fallingbacktodefaultprofiles:default
20:34:28.117[main]INFOc.j.demo.Spring_boot_junit5_api_test-StartedSpring_boot_junit5_api_testin17.961seconds(JVMrunningfor21.668)
20:34:30.716[http-nio-auto-1-exec-1]INFOc.j.controller.HelloController-testinfolog:Peter
20:34:30.719[http-nio-auto-1-exec-1]DEBUGc.j.controller.HelloController-testdebuglog:MessageDto(id=1,message=HelloPeter,Thanksforthesubscription!)
3.Conclusion
Inthisarticlewewalkedthroughasimplespringbootexampleapplication,whichhelpstostartworkingwithLombokandSpringboottogether.YoucanreferDelombokMavenexampletoseehowlookslikelombokgeneratedcodeforyourLombokedclasses.
Youcangetsourcecodeatourgithubrepository.
YoumightbeinterestedinourotherfollowingLombokTutorials:
Lombok@Getter@SetterandlazygettersLombok@ToStringLombok@EqualsAndHashCodeLombok@AllArgsConstructorLombok@NoArgsConstructorLombok@RequiredArgsConstructorLombok@NonNullLombok@Value
reportthisad
Lombok
Tagslombokspringboot
PreviousarticleLombok@Slf4jExamplesNextarticleDelomboking–delombokmavenconfigurationExample
LEAVEAREPLYCancelreply
Comment:
Pleaseenteryourcomment!
Name:*
Pleaseenteryournamehere
Email:*
Youhaveenteredanincorrectemailaddress!
Pleaseenteryouremailaddresshere
Website:
Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment.
reportthisad
reportthisad
javabydeveloperJavaTutorials
javabydeveloper.comjavabydeveloper.comistheindependentresourcebyenterpriseJavatechnologydevelopersfordeveloperswhowanttolearnaboutJavamostpopularandrelatedtechnologies.Ourprimarygoalistoprovidesimpleandeffectivetutorialswithwelltestedworkingexamplesforthealllevelofdevelopers.
©2015-2022javabydeveloper.com|Allrightsreserved
DESCLAIMER
Alltrademarksarethepropertyoftheirrespectiveowners,whichareinnowayassociatedwithjavabydeveloper.comjavabydeveloper.com.JavaisatrademarkorregisteredtrademarkofOracleCorporation.ExamplesatjavabydeveloperisnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation.
ABOUTUS
AboutUsPrivacyPolicyContactUsSiteMapCompanyInfo
PopularCategories
CoreJavaJPAHibernateJava8SpringBootJunit5LombokMaven
xx