You are on page 1of 13

Chapter-01

Spring Boot Core


Spring Boot:
- Spring Boot is one approach to develop Spring Based applications with less
configurations.
- Using Spring Boot we can develop below types of applications
 Standalone app
 Web
 Distributed (Restful webservices)/Microservices/Spring Cloud

Note:
- By using Spring core recommended to develop Web Application (Spring MVC).
- By using Spring Boot recommended to develop Restful webservices/ Microservices/
spring Cloud applications.

Difference Between AWS cloud and Spring Cloud?


- Spring cloud to develop application using Microservices Architect
- AWS cloud to run/ deploy the applications.
Advantages of Spring Boot:
- Starter Pom (simplifies Maven/Gradle build configuration)
 Spring-boot-starter-web
 Spring-boot-starter-data-jpa
 security-starter
 mail-starter
- Auto Configuration: Spring boot will identify required configs for our application.
 Start IOC container
 Component Scanning
 deploy web app in embedded server
- Actuators: To monitor and manage our application.
 how many beans loaded?
 How many URL-patterns mapped?
 What is health of app?
 Heap Dump
 Thread Dump
- Embedded Servers: It provides server to run our boot application.
 Apache Tomcat (default)
 Jetty
 netty
Chapter-01
Spring Boot Core
How to Create Spring Boot Application?
- We can create Spring Boot application using Initializer website (start.spring.io) and
- IDE
Note: IDE will internally connect with start.spring.io website to create Spring Boot
application (Spring Starter Project).

What is Start Class in Spring Boot?


- Start class is entry point for boot application execution.
- Start class is also called as main class in Spring Boot.
- When we create boot app, start class will create by default.
Starter Class Example:

1. package org.nadim;
2.
3. import org.springframework.boot.SpringApplication;
4. import org.springframework.boot.autoconfigure.SpringBootApplication;
5.
6. @SpringBootApplication
7. public class Application {
8.
9. public static void main(String[] args) {
10. SpringApplication.run(Application.class, args);
11. }
12. }

What is @SpringBootApplication annotation?


- The @SpringBootApplication annotation can be used to enable three features, that is:
 @ComponentScan
 @Configuration
 @EnableAutoConfiguration
Chapter-01
Spring Boot Core
How IOC starting in Spring Boot?
- SpringApplication.run ( ) method contains logic to start IOC container.
- Which class is starting the IoC container depend on starter we have added on
Maven/Gradle.

Examples:
- When we add a dependence “spring-boot-starter” in Maven/Gradle for standalone
application our starter class run() method internally use
“AnnotationConfigApplicationContext” is the class to start or create IoC container.
- When we add a dependence “spring-boot-starter-web” in Maven/Gradle for
standalone application our starter class run() method internally use
“AnnotationConfigServletWebServerApplicationContext” is the class to start or
create IoC container.
- When we add a dependence “spring-boot-starter- webflux” in Maven/Gradle for
standalone application our starter class run() method internally use
"AnnotationConfigReactiveWebServerApplicationContext" is the class to start or
create IoC container.

Starter Class run () method:


- run() is a static class present inside “SpringApplication” class.
- The return type of run() is “ConfigurableApplicationContext(I)”
- Internally this run() method performs a lot of task.
Some Tasks are:
- Set up the initial configuration
- Start the IoC container
- Starts the application context
- Scanning the Class Path
Chapter-01
Spring Boot Core
What is Banner in Spring Boot?
- This is nothing but logo (never shown to enduser) printed at console while starting
application.
- We can override this using a file created manually at src/main/resources name is:
“banner.txt”
We have below 3 modes for banner.
 console (default) --->> prints on console
 log ---->> prints on log file
 off --->> don't print banner

We can set banner mode in 2 ways.


1. Using-

1. package org.nadim;
2.
3. import org.springframework.boot.Banner.Mode;
4. import org.springframework.boot.SpringApplication;
5. import org.springframework.boot.autoconfigure.SpringBootApplication;
6. import org.springframework.context.ConfigurableApplicationContext;
7.
8. @SpringBootApplication
9. public class Application {
10.
11. public static void main(String[] args) {
12. SpringApplication sa = new SpringApplication();
13. sa.setBannerMode(Mode.OFF);
14. }
15. }

2. We can set banner mode in application.properties file.

1. spring.main.banner-mode=off

ASCII Text Gen Url : https://patorjk.com/software/taag/#p=display&f=Graffiti&t=SBI%20API

What is Runner in Spring Boot?


- Spring Boot provides Runner to execute any logic only once by Spring Container
while starting our application.
Chapter-01
Spring Boot Core
What is the need/advantages using Runner in Spring Boot?
(OR)
Purpose of runner?
- Testing, Objects are Created or not?
- Loading Database Scripts
- Root user creation/Roles setup.
- Loan static tables (non-transaction/select query) data when application starts
- Delete data from staging tables (clean temporary table data)
- Send Notifications regrading Application startup

Note:
- We can define multiple runners in one application.
- They are executed in Alphabetical naming order
- We can provide our own order using @Order(int) annotation. If no annotation
@Order is provided then default value is Integer.MAX_VALUE (2147483647).
- If multiple Runners are having same order, then again naming rule is applied.

We have 2 types of Runners in Spring Boot


 CommandLineRunner (I)
 public abstract void run (String ...args);
 ApplicationRunner (I)
 public abstract void run (ApplicationArguments arg);

Note: Both are functional Interface. They are containing only one method

What is Functional Interface?


A functional interface in Java is an interface that contains only a single abstract
(unimplemented) method. A functional interface can contain default and static methods
which do have an implementation, in addition to the single unimplemented method.

Coding Steps:
1. Define one class and add @Component
2. implement CommandLineRunner/ApplicationRunner and override run() method
3. Define your logic inside run method.
Chapter-01
Spring Boot Core

Another Way to Define runners:


Implement CommandLineRunner in @SpringBootApplication
Chapter-01
Spring Boot Core
@ConfigurationProperties

- @Value will try to read one key data from “application.properties” file and if key is
found inject data into one variable, else key not found then container throws
exception.

-
- @Value we can use only one time per variable. So, if we have n number of variables
to load n number of keys then we should define @Value over n number of variables.

To Avoid those limitation, we can use @ConfifurationProperties annotation


@ConfigurationProperties:
=======================
- “@ConfigurationProperties” loads all keys data into matching variables at a
time by writing this annotation only one time per class with the help of prefix.
- “@ConfigurationProperties” will never throw any exception if
keyname/variable name not matching or prefix is not matching or setters not
found, all these cases variable holds default value (null/0/0.0/false).
Chapter-01
Spring Boot Core
Note:
- Here we should not use @Component over child class and @Autowired over
HAS-A reference variable when we are using @ConfigurationProperties.

Why?
- “@ConfigurationProperties” creates child class object based on condition,
saying that if data is present (at least for one variable) inside child class then
create object and link.

Application.properties file
=======================
- .properties file will store data in key=val format. Where key are case-sensitive.
- If same key is provided multiple time with different value then last combination is
taken.
- Symbol # indicates comment in properties file.
- You can use _(underscore) . (dot) - (dash) symbols in key name.
o Example: my.app. std-name = value
my.app_name.gender = value
- Auto parsing is supported based on variable datatype. By default key and value
(both ) are String datatype.

1. my.app.name = Service
2. my.app.service.code = 102
3. my.app.service.vaucher = debit
4. my.app.port-number = 8080
Chapter-01
Spring Boot Core
Primitive Data representation
- Syntaxt
prefix.variableName = value

Array/Collections data Representation


- For array, list, set prefix.variableName[index]=value (or)
prefix.variableName = value1,value2…..valueNth

- For Map, prefix.variableName.keyName = value

Reference Data Representation


Syntext:
Chapter-01
Spring Boot Core
Prefix.referenceName.variable = value

YAML (.yml) File


==============
- YAML (.yml in Spring boot / .yaml ) is used to represent data/input to pre-defined
configuration.
- YAML is better compared to properties
- Occupy less memory
- Less processing times
- More readable

Note:
1. No Duplicate Levels in YAML file
2. Every level should end with either :<NextLine> or :<oneSpace><value>
3. Every new level start (not for 1st line) must have same space count (indentation) [at least
one space]

4. In case of List/Set/Array , index is represented using - (dash)


app:
variable:
Chapter-01
Spring Boot Core
- value
- value
- value

5. In case of Map/Properties, key:<space>value


app:
variable:
mapKey: mapVal

6. In case of Reference type, variable:<space>value


app:
refVariable:
variable: value

Q) Why are we using .properties / .xml / .yml files here?


Chapter-01
Spring Boot Core
- To starting our application Some data is required like Database Connection,
JPA(Hibernate) Details, Email Config, Security Configuration etc.

=====================
Project Lombok API
=====================
- It is a Java Open-Source API, used to generate source code before we compile
the code. After compiling the source code, .class file will be generated. For run
the .class file Lombok is not required.
- We need to add, activate Lombok JAR and use all annotations.

===============================
Step to Activate Lombok API:
===============================
I. After Creating stater project in pom.xml add Lombok maven dependency-
1. <dependency>
2. <groupId>org.projectlombok</groupId>
3. <artifactId>lombok</artifactId>
4. </dependency>

II. Update Maven Project and close IDE

III. Activate Lombok for our IDE go to below location-


a. C:\Users\ADMIN\.m2\repository\org\projectlombok\lombok\1.18.24

IV. And double click on “lombok-1.18.30.jar” (or execute cmd: “java -jar lombok-
1.18.24.jar” file and select IDE and click on install and Update Button.
V. Quit Installer.

======================
Lombok Annotation:
Chapter-01
Spring Boot Core
======================
1. @Setter: generates set methods
2. @Getter: generates get methods
3. @ToString: override toString logic
4. @EqualsAndHashCode: generates equals and hashCode methods
5. @NoArgsConstructor: Default/zero param const
6. @AllArgsConstructor: All variables selected to create one parameterized
constructor.
7. @RequiredArgsConstructor + @NonNull: To generate selected parameters
constructor. @NonNull use over the specific variables which variables are used as a
constructor parameter.
8. @Data: This one is used to generate set/get, toString, equals, hashCode and
Required Args Constructor.

You might also like