Spring Boot Tutorials
Table of Contents
Spring Boot Tutorials:
1. Spring Boot – Is it a Brand New Framework ?
Spring boot is not a brand new framework, just like mvc/web/rest/jpa add-ons, it’s just a additional kit from spring to reduce the development headaches with spring framework.
2. How to configure spring boot in Maven ?
Spring boot provides single dependency entry for pom.xml configuration,
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
Here this downloads all the dependencies required for web spring boot applications.
Version 1.5.10 represents the version of the spring boot(not any spring core/context jars) and equivalent version mappings for all the needed jars like spring-context, spring-core will be downloaded automatically, what versions of each dependency will be downloaded or mapped can be found here,
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot/1.5.10.RELEASE
3. How we come to know is this a spring boot application or not ?
Like in core java, spring boot application will also have main class with the configuration specified below,
SpringApplication.run method should be called out in your main method to run as embedded spring boot project, If you create spring starter project in STS, then you do not want to do anything, spring boot itself will configure all this for you.
@SpringBootApplication public class MyFirstSpringBootApp{ public static void main(String[] args) throws Exception { SpringApplication.run(YOUR_CLASS_NAME.class, args); } }
and it launches an embedded web server for you. By default you will get tomcat as embedded server, but still you can change to any servers like jetty etc.
Ensure the main class annotated with <code>
@Controller & <span class="nd"><strong>@EnableAutoConfiguration</strong> atleast.</span>
Related spring boot article:
Restful Web services with Spring boot Simple Example
4. Do we need web.xml in spring boot ?
Spring boot does not require web.xml and everything can be configured through annotations only.
@Configuration annotation should be used for classes where you want to add the filters and listeners and @Bean annotation can be used to add the filter mapping in spring boot Main class. (earlier the same has been done in web.xml)
Related spring boot article:
Scheduler in Spring Boot with 3 Simple Steps Example
5. Very Simple Spring Boot Rest Controller
7. Spring Boot will detect that you have a Spring MVC controller If you have @ComponentScan in main java class and @RestController anywhere and start up an embedded Apache Tomcat 8 instance, by default.
You should be able to test the REST endpoint by opening up your browser and hitting http://localhost:8080/hello/ngdeveloper.com will print Hello, ngdeveloper.com
here 8080: default port number
hello: your contextpath
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } @RestController class GreetingController { @RequestMapping("/hello/{name}") String hello(@PathVariable String name) { return "Hello, " + name + "!"; } }
6. How to set/change application port number in spring boot ?
server.port=13123
7. How to set context path in spring boot ?
server.servlet.contextPath=/ngdeveloper/api
8. Where to configure DB, SSL, context path, cache etc. ?
application.properties is the one and only property file which helps to configure hibernate/ehcache/application config’s like context path, port number, compression, cache etc…
Related spring boot article:
Spring Boot + EhCache Hibernate Working Example
9. How many XML files required for Spring Boot to run successfully?
pom.xml is the only xml file used in spring boot project. No more web.xml or deployment descriptors with spring boot. All the annotated classes and methods are internally loaded and managed by spring without web.xml file.
10. How to solve LazyInitializationException in Spring Boot?
Are you getting the below error in your spring boot + hibernate project,
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: , could not initialize proxy - no Session
Then the same can be resolved either adding @Transactional to your service/controller method level (or) by adding the below entries in your application.properties file,
[code]
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
[/code]
This may create N+1 problem as well, so properly test & use to keep or not for your use case.
11. How to add SSL certificates to your spring boot project ?
You need to add the below application.properties for ssl certificates, here you need to have keystore.p12 file, which can be generated from SSL certificates.
server.port=8443 security.require-ssl=true server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=YOUR_CERTIFICATE_SECRET_PASSWORD server.ssl.keyStoreType=PKCS12 server.ssl.keyAlias=tomcat spring.datasource.hikari.maximum-pool-size=5
Related spring boot article:
Creating keystore.p12 from letsencrypt certificate for spring boot projects
12. How to show Hibernate/Spring JPA Queries ?
spring.jpa.show-sql=true
13. How to add/configure RabbitMQ ?
Add the below entries in your application.properties file to add RabbitMQ to your spring boot microservice application.
spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.rabbitmq.listener.simple.acknowledge-mode=auto
Related: Creating RabbitMQ Listener in Spring Boot
14. How to enable HTTP/2 support in Spring Boot?
Add the below entries in application.properties file,
server.http2.enabled=true
15. How to enable compression/gzip compression in Spring Boot?
Add the below entries in application.properties to enable gzip compression,
# true to enable compression server.compression.enabled=true # add all needed mime types here server.compression.mime-types= text/plain,text/xml,text/css,text/cache-manifest,text/vcard,text/vnd.rim.location.xloc,text/vtt,text/x-component,text/x-cross-domain-policy,application/atom+xml,application/ld+json,application/manifest+json,application/rss+xml,application/vnd.geo+json,application/json,application/javascript,application/octet-stream,application/xml,application/x-javascript,text/javascript,application/vnd.ms-fontobject,application/x-font-ttf,application/x-web-app-manifest+json,font/opentype,image/svg+xml,image/x-icon,image/bmp,image/jpg,image/png,image/jpeg,image/webp # compress only if more than 1KB server.compression.min-response-size=1024
16. How to configure EhCache in Spring Boot?
Ehcache is one of the great stuff to increase the performance of your application,
Enable in application.properties
spring.cache.ehcache.config=classpath:ehcache.xml
And create ehcache.xml file like below,
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <cache name="couponsCache" maxElementsInMemory="1000" eternal="false" overflowToDisk="false" timeToLiveSeconds="30000" timeToIdleSeconds="0" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> </cache> </ehcache>
Then you have to use ehcache in your DAO/Repository like this,
@Cacheable(value = "couponsCache") List findByUserOrderByUpdatedTimeDesc(User user);
Read More here: Ehcache + Hibernate + Spring boot Working Example
17. How to configure spring boot to send mail (gmail) or smtp email ?
Add the below properties in application.properties file,
#Mail related spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=<YOUR_GMAIL_USER_NAME>@gmail.com spring.mail.password=<YOUR_GMAIL_PASSWORD> spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.test-connection=true spring.mail.properties.from.email=<YOUR_GMAIL_USER_NAME>@gmail.com spring.mail.protocol=smtp spring.mail.properties.mail.smtp.connectiontimeout=5000 spring.mail.properties.mail.smtp.timeout=3000 spring.mail.properties.mail.smtp.writetimeout=5000 spring.mail.default-encoding=UTF-8
Are you getting connection refused error while trying to send mail through gmail / during startup when the test connection is enabled, then you have issue with your firewall/antivirus. Block the both and test, it will be working without any issues.
18. How to send html tables in the email(gmail) body through spring boot?
Use the below code snippet when you wan to send html tables in the gmail / email through spring boot using java mail sender library.
Snippet to Send HTML Table in Email Body Through spring boot:
import org.springframework.mail.javamail.JavaMailSender; @Component public class MailService { private final JavaMailSender sender; @Autowired public MailService(JavaMailSender sender) { this.sender = sender; } public void sendHtmlTableEmail(){ mainString = mainString.concat("<html><head><title>NgDeveloper </title></head><body><table style=' width: 100%;\r\n" + " margin-bottom: 1rem;\r\n" + " background-color: transparent;border-collapse: collapse;border: 1px solid #dee2e6; border-spacing: 2px; display: table;\r\n" + "' border=\"1\"><thead>" + "<tr style='display: table-row;\r\n\" + \r\n" + " \" vertical-align: inherit;\r\n\" + \r\n" + " \" border-color: inherit;'><td style='padding: .75rem;\r\n\" vertical-align: top;'><strong>Store</strong></td><td style='padding: .75rem;\r\n\"" + "\"vertical-align: top;'><strong>Link</strong></td></tr></thead><tbody style='display: table-row-group;\r\n" + "vertical-align: middle;\r\n" + "border-color: inherit;'>"); // added flipkart store and link mainString = mainString.concat("<tr style='display: table-row;\r\n" + " vertical-align: inherit;\r\n" + " border-color: inherit;'><td style='padding: .75rem;\r\n" + " vertical-align: top;'>Flipkart</td><td style='padding: .75rem;\r\n\" + \r\n" + mainString = mainString.concat("</tbody></table></body></html>"); sendHtml(<MAIL_ID_TO_BE_SENT>, MAIL_SUBJECT,mainString); } public void sendHtml(String emailTo, String subject, String body) { MimeMessagePreparator message = newMessage -> { newMessage.setRecipient( Message.RecipientType.TO, new InternetAddress(emailTo) ); newMessage.setSubject(subject); newMessage.setContent(body, "text/html"); }; this.sender.send(message); } }
Snippet to Send Email Through spring boot:
import org.springframework.mail.javamail.JavaMailSender; @Component public class MailService { private final JavaMailSender sender; @Autowired public MailService(JavaMailSender sender) { this.sender = sender; } public void send(String emailTo, String subject, String body) { MimeMessagePreparator message = newMessage -> { newMessage.setRecipient( Message.RecipientType.TO, new InternetAddress(emailTo) ); newMessage.setFrom("YOUR_EMAIL_ID"); newMessage.setSubject(subject); newMessage.setText(body); }; this.sender.send(message); } }
19. How to enable security logging to debug spring security / filter calls in spring boot ?
Sometimes we will just see the exception or error as “401 unauthorized”, but it is quiet difficult to understand in which area it is failing (means due to any filters) or any issue in the spring security configurations etc, so add the below line to your application.properties file to debug the spring security call sequences,
logging.level.org.springframework.security=DEBUG
20. How to fix spring actuator health status shows as “DOWN” always issue ?
By adding the below line to your application.properties file, you will be able to see the status as
{"status":"UP"}
management.health.defaults.enabled=false
Still not able to see then try adding the below entries as well in the application.properties file,
endpoints.health.sensitive=false management.security.enabled=false
21. How to use profile/profiling like dev/prod/testing etc in Spring Boot?
Like application.properties, create
- application-dev.properties,
- application-prod.properties
- application-testing.properties
Each file will have different configurations then while running/debugging your spring boot microservices, make sure to add profile name like this,
Then you can able to see like this in your console,
<It reads all the configurations from application-dev.properties file>
By default without the above VM arguments profile setting, console prints,
<By default it reads all the configurations from application.properties file>
22. How to add lombok dependency to your Spring Boot application ?
Add this maven dependency:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency>
in Your DTO’s/Beans/Entities add the getter and setters this way,
@Data @Getter @Setter @ToString @JsonInclude(JsonInclude.Include.NON_NULL) public class SignupV2Request { @NotNull private String mobile; @NotNull private String name; @NotNull private String email; @NotNull private String otp; @NotNull private String password; private String message; }
Do you have something to add here ?
Feel free to comment in the below comments section.
Learn from anyone, teach atleast someone.
References: