0% found this document useful (0 votes)
45 views

spring core + spring boot+thymleaf+microservices

Uploaded by

er.pramod05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

spring core + spring boot+thymleaf+microservices

Uploaded by

er.pramod05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 168

SPRING CORE & SPRING BOOT with MICROSERVICES

SPRING CORE
->To learn spring boot the minimum requirement is to know about spring core . if you
know spring core very well and foundation is clear then you are eligible to learn spring
boot and go a head.

->spring comes with various modules . and spring boot is top of all that means if we talk
about spring boot spring boot internally uses all of these modules. But to go ahead with
spring boot we should know atleast about spring core.

Note:- spring boot is not a new technology or framework or alternate for spring actually
spring boot internally uses all these modules only.

->before spring there is EJB but it was very complex to write so,ROD JOHNSON think how
to develop enterprise application without using EJB ,so to reduce complexity and increase
productivity he developed a framework called SPRING in 2003 so from that time to till
date spring and springboot is ruling the market.

Before go ahead with spring core ,let see the software requirement for spring

-> java JDK (minimum version jdk8)

->eclipse or STS(spring tool suit) or any other..


->maven:- it comes with eclipse /sts so no need to download it externally .

2 major component of spring core.[ Spring core = IOC + DI]


->inversion of control (IOC)

->dependency injection (DI)


Inversion of Control:
->The design pattern responsible for handling the creation of objects defined in the
configuration and providing that to application. In simple words giving the control of
creating and instantiating the object to IOC container. our spring IOC container takes the
responsibility to create and manage the objects only developer need to tell IOC container
in form of configuration that he requires that object ,

->in spring for configuration we can use Xml based configuration or annotation based
configuration. (annotation based recommended).

->spring IOC container is also called application context

->Note:- as we know IOC container create and instantiating the object but we not use
word “Object” in spring because this object is managed by our IOC so we called it “Bean”
because its life cycle is managed by IOC.

Steps to create spring first program.


->open eclipse/STS or any IDE

->create maven project


Why Maven Project ?
->see Maven is build tool ,we will learn about maven later it is separate topic but as off now just for
knowledge you remember that maven is build tool which help developer to import 3rd party libraries from
external source (MVN repository).

->see when we develop any project let take example of spring project then we requires lot of libraries
which present in external source like MVN repository then if we manually download each and every
library then it take lot of time as well as version mismatch issue can also occur and lot of issue may come
so maven build tools is came into picture

->maven tool automatically downloads all the dependent libraries from mvn repo and import it to our
application without any version mismatch issue.

->this is not complete picture of maven but for as off now its enough.

->after that select maven-archtype-quickstart.(just to create simple maven


standalone project and it give basic structure as well as boiler code)
->now put project details.

Group Id:- you need to tell your project comes under which group ex:- suppose in your
company lots of project are developed related to finance department and this project also
related to finance only so you can say that this project comes under finance group that is
nothing but group id.

artifact id:-artifact id means here you need to tell purpose like your project belongs to
finance group but under finance there are so many things our project related to which
thing we need to specify here.ex:- under finance our project related to loan.

Version:- here you need to specify project version.

Package:-just specify project package in which package you need to put your
project.

->click on finish.
Note:- maven internally download all the dependency from maven central
repository.

->if you want any dependency just go to maven repo and copy dependency tag from
there at paste to POM.xml file maven itself download that in your project.

Ex:-

NOTE:- here i am using spring version 5.3.19 it is not mandatory to use same version
because in spring frequently new version is realised . if this version is not worked or
compatiable then try another version. Take any stable version by your own.
->we have created project but still it is maven project only to make it spring project and to
use spring core functionality we need to add spring-context dependency .to add this
add spring-context dependency in POM.xml.

->go to maven repository search spring-context and add in pom file.

Note:- maven first see in local repository in your system if it available there then it use it
from there otherwise it download from internet.

->maven also see version if dependency already present in local but it is not compatiable
with version then it download again from central repo.

Local repo:- path-> c:\Users\codemines\.m2\repository


Now to change default JDK configuration in eclipse if required then follow
these steps.
In above we have change old jdk to new jdk as well as compiler config also and here we
are ready to go ahead.

->as of now we know how to create maven project and how to make it spring project by
adding spring-context dependency using POM file with help of maven build tool.

->we have also seen about IOC container .what is IOC ,what it responsibility now we will
see these topics indeep.

Overll small picture get cleared now go deep dive inside these topics..
Configuration file
->as we know in spring .IOC will create bean and provide it in our application
but we need to defined configuration regarding that means what kind of bean
we need so that IOC container/application context can full fill our demand.

->we can give configuration in two ways

1)XML based approach

2)annotation based approach (recommended)

XML based approach


->in this approach we will make one xml file and defined all bean related
configuration there and IOC container will read that configuration from that
XML file and create & initiate bean depending on configuration you have written
in that XML file.

->but where to keep that configuration XML file because we get one project
structure and there are to lots of different –different packages and folder..

So to keep XML configuration file we need to make one “resources” folder in


eclipse. In spring boot bydefault this “resources” folder comes we no need to
create there.
When you create xml file for configuration then we need to write xml
tags inside it for configuration so to start any tag first we need to write
basic xml schema which you no need to remember you can just see it
from net .
See basic schema

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- write beans configuration here -->

</beans>
Now we have one class suppose
->we have Loantaxcalculator class and we need it object but we don’t want create
manually. we want that IOC contaire will create and give to us then we will defined
that in configuration xml file that we want that Loantaxcalculator bean.

myappconfig.xml

->we have created configuration XML file and also define <bean> tag that we need this
class bean, now give this configuration file to IOC container/application context.

->inside main class

ApplicationContext context= new ClassPathXmlApplicationContext("myappconfig.xml");

ClassPathXmlApplicationContext: This container takes the path of xml file from the
classpath and loads the definitions of the beans from an xml file. means
classpathxmlapplicaioncontext will recoginized where this myappconfig.xml in the
classpath means in the project ..and read that configuration file and create its object.
->ApplicationContext is nothing but IOC container. Now in above code your
bean get created .now to use that bean we need to get it from IOC container
so we use getBean(unique_bean_id) method.

Some steps summary

->first create maven project and add spring-context dependency.

->make resource folder if it is not there.

->define configuration xml file.

->create main class and create ApplicationContext as well and get bean with
that unique bean id.

You can also use :-


Bean Factory Container
Resource resource = new FileSystemResource(“appbeans.xml”);

BeanFactory factory = new XmlBeanFactory(resource);


->ApplicationContext is more preferred way and also recommended.

->applicationContext will follow eager loading that means whenever IOC starts
immediately it will create bean objects.

->BeanFactory will create bean object on demand basis that means when we
call getBean() method then only it will create bean object (lazy loading).

->in general if you need to set class property value then we can simply set by
using setter and getter , but we want so set from configuration xml file then we
can set it by <property> tag inside bean.

Ex:

Myconfig.xml
Main class

Dependency injection
->as off now we have seen bean creation using configuration xml file. Now we
deep dive into most important topic that is DI (dependency injection).

Let first know what is dependency means. See if one class object requires or
need another class object for some operation or business logic then we can
say that one class is dependent on another class.

Ex:- we have one Car class and we have one Engine class then car class requires
Engine class object which means Car class is dependent on Engine class.
Ex:-
Note:-if we use <property> tag for injection then it uses setter method .which means
setter injection happens. The property name should match with the setter method
property name of the class. The ref bean value should match with bean id value in the xml
file.
We have seen how to set normal property using <property> tag and how to inject
dependent bean using ref attribute. Setter method injection is one way we have another
way also ..

Dependency injection using constructor


->as we know that we can set class property by using setter method right core java
concept and we also know that we can also use constructor to initialize class property. So
we can also use constructor to perform dependency injection.

Constructor arg:

<constructor-arg>

<ref bean= “org” >

</constructor-arg>

->it will inject that bean using constructor . you can use both either setter or constructor
but in constructor injection you need to maintain constructor parameter order in which
order parameter are present in constructor in same order you need to pass value from xml
file.

->in constructor if by mistake parameter order changes then it will cause issue so to solve
it we can use one more attribute called index.

->now using index attribute it is not mandatory to maintaine order just you need to write
correct index
->as off now we have seen how to inject single dependency now we will see how to inject
list of dependencies

Using setter

Same thing you can perform with constructor injection also..


->same logic we can perform with constructor injection ...

->for map value

->same concept apply using constructor injection..

Autowiring
->as off now in above cases we are doing manually wiring of objects means we are
injecting beans using <ref> tag and all inside property tag or constructor arg tag.

->but for small number of objects it’s ok but in real time there are lots of object we
require to inject then this manual wiring approach is not recommended just for ex if we
have 50 object then we need to write 50 bean tag and inject it .it become complex .

->to solve this autowiring came into picture. Auto wiring solve all the manual
dependencies specified in the configuration and make DI simple.

Now in autowiring we have 3 types:


1)byname

2)byType

3)constructor

Autowiring byName
-> The dependent property name (variable) in the class is matched with bean id in the
configuration file and if they are matched then ioc will inject that particular bean by using
setters simple

->above we just mention autowire=”byname” IOC automatically inject that dependent


bean.

Autowire by Type
->in this dependent property type in the class is matched with the bean class type. If both
are matched then IOC container will inject that specific bean. We need to use
autowire=”byType”.

->Note:- if more then 1 bean is found with same class type in XML configuration
file,autowire byType give error. We can fix this in annotation based configuration.

->autowired byType means ico will match type not bean id so you can give any bean id.

Autowire by constructor
->autowire by constructor uses constructor for dependency injection.
->autowire by constructor first inject bean based on its type means if
type matched then it inject that particular bean.
Note:- we have seen that if more then 1 bean having same type then
autowire byType generate exception. But when we use autowire by
Constructor. Then first it matched on the basis of by Type but if ioc
found more then 1 bean with same type then IOC will try to match
constructor parameter name with bean id .if matched then it will
perform the injection otherwise raise an exception.

Annotations based configuration


->as we seen in XML based configuration that we need to create separate XML
file and IOC will read it and perform DI etc. But this is little stressful for
developer , developer need to remember lots of XML tags as well as need to
maintain separate XML file .

->to solve above problem annotation came into picture. Actually in java
annotation introduced from java 5. Now spring provides lots of annotation and
now IOC will read that annotation and perform its task now no need to
maintain separate XML file for that.

->let discuss some of most important annotation .


Some Important annotations in Spring IOC and DI

@Configuration : @Configuration indicates that the class has @Bean


definition methods or @Component scan to scan for the @Component so that
Spring Container can process the class and generates Spring Beans tied to
application Context

@Bean : Method level annotation used to explicitly declare a Spring Bean

@Component: Class Level annotation which will be detected by


@ComponentScan for creating Spring Beans

@Autowired: Enables to inject the object dependency, can be used on Setter


method, field, Constructor

@Qualifier: if there is more than 1 bean with same class type, using @Qualifier
we can match the bean id to be injected

@Qualifier is placed along with @Autowired

@Primary: If we can declare @Primary in any of the @Bean/@Component,


then by default the bean

with @Primary gets injected if there is a conflict in autowiring of the beans


with same class type provided there is no @Qualifier matching present

@Scope : Indicates the name of the bean scope to be used like


Prototype(default is singleton if no @Scope is present). Can be used along with
@Bean or @Component

@Lazy : Indicates the lazy loading of Bean , can be used along with @Bean or
@Component

@ComponentScan: Scans for the @Components in the specified base package,


default base package is the package where @Configuration class is present
->in annotation based approach we no need to make any separate XML file
.instead of that we make our java class as a configuration by using
@Confguration annotation at class level.

->like in XML approach in xml configuration file we declare bean by using


<bean> tag. Similarly in annotation approach we create bean annotated
method by using @Bean annotation,so IOC will call that @Bean annotated
method and return the object.

In main class to load configuration class we need to use

ApplicationContext context=new
AnnotationConfigApplicationContext(AppConfig.class);
->now if we want to inject some dependent object using annotation then we
can go with

@Autowired
Note:- by default @Autowired inject bean by matching ‘byType’ if same type
of bean is present then it inject on basis of byname. In annotation this single
annotation will work both byType ,byname.(in xml we need to mention separate
byname,ByType)

->as we know @Autowired work bydefault byType . if more then one bean
existed with same type then it goes with byname.

->if in case ioc not get any bean byname also then it cause issue.
Note:- if you not create any setter then it implicitly inject using internal setter using
reflection api concept.

@ Qualifier
->if there is more than 1 bean with same class type, using @Qualifier we can
match the bean id to be injected @Qualifier is placed along with @Autowired.

->means if we have more then 1 bean of same type then @Autowired will
work byName but if bean name also not match in that case it will cause issue.
We can use @Qualifier annotation and specify the name so now qualifier
name must match with bean name ,it doesn’t matter what ever is property
name
@Component and @ComponentScan
->@Component: Class Level annotation which will be detected by
@ComponentScan for creating Spring Beans.
->@ComponentScan: Scans for the @Components in the specified base package, default
base package is the package where @Configuration class is present.

->in case of @Configuration we need to declare @Bean annotated method to create bean
,but suppose we need 50 bean then we need to create 50 bean methods . but here we
have one another class level annotations i.e @ComponentScan and @Component

->@ComponentScan will scan for @Component and wherever it sees


@Component ,spring ioc will create the bean automatically.

->both @ComponentScan and @Component are class level


annotations.means we can use it on class level only.

->@ComponentScan is always associated with @Configuration annotations.


Means when we make our configuration class by using @Configuration then
we need to write @ComponentScan annotation also .

->now if you want bean of any class then declare that class with @Component
annotation so that IOC will automatically scan it and create bean for you.
->if you want to give another name of bean instead of class name then you can
provide in @Component(“name”).
@Primary: If we can declare @Primary in any of the @Bean/@Component,
then by default the bean

with @Primary gets injected if there is a conflict in autowiring of the beans


with same class type provided there is no @Qualifier matching present
Above example two bean with same type ,we have given bean name like
dept,dept1 but there is no any @qualifer annotation so now ioc will confuse
.but we have also provided @Primary so IOC will give more priority to ‘dept1’
bean and inject it.

->if you have used both @Qualifier as well as @primary annotation then IOC
will give preference to @Qualifier first then @Primary.

Bean Scope
Singleton – Same object returned for the same bean id per application context.

Prototype – Different object returned for the same bean id per application context.
-> bydefault every bean is singleton ,if we need to define the scope of bean as prototype
,we should declare the scope of bean as prototype during bean declaration.

as we know we have 2 approches to create configuration

->XML based approach.

->annotation based approach.


Prototype scope

->in this different bean will created every time in per application context.

Lazy and eager Loading


Eager Loading – Spring Beans are created during the application context creation.

Lazy loading – Spring Beans are created during the context.getBean creation.

->by default it follows eager loading. Means bean are created during the time
of application context creation.
Bean Life cycle

@Autowired on Constructor
case 1:

in the class with @Component .suppose if we have exactly 1 parameterized constructor,


this gets called even if we have @Autowired or do'nt have @Autowired on the constructor

case 2:

in the class with @Component if we have more than 1 parametrized constructor, then one
of the constructor should be @Autowired otherwise it will throw error.

case 3:

in the class with @Component if we have more than 1 parametrized constructor, then if
we decalre @Autowired on more than 1 parametrized constructor, it will throw error

case 4:
in the class with @Component if we have 1 parmeterized constructor and 1 default
constructor(constructor without arguments) then default constructor gets called if the
parmeterized constructor does not have @Autowired otherwise the parameterized
constructor gets called where @Autowired is present.
Spring boot
->Spring boot is an open source java-based framework developed by Pivotal
Team.

->spring boot makes developer life easy by auto-configuring everything and


helps to create production grade spring based application.

->spring boot simplifies the bootstrapping and development.

->spring boot was designed on the top of existed spring framework only it
internally uses all spring modules .

->spring boot can used to develop spring based application either by JAVA or
by Groovy.

->it improves productivity and reduces development time.

->Spring boot follows “Opinionated default configuration” approach to reduce


developer efforts ,that is Spring boot avoids writing lot of boilerplate
code,annotations and configuration.

->Spring boot provides embedded HTTP servers like Tomcat,Jetty etc.

->spring boot also provide build tool like Maven , Gradle to develop
application.
->it also provide In-Memory database also ex:- H2

->it provides YAML support also for properties.

Note:- if we are using plain spring then developer need to take care of
everything i.e business logic + lots of configuration.

Note:- if we are using spring boot then developer can focus on its business
logic and rest all configuration will be taken care by spring boot.

->spring boot is famous for auto-configuration feature which is one of the main
feature of spring boot.

->based on starter POMS it will identify what configuration required.

Ex:- if we define web-starter ,spring boot will provide web related feature like
give support of server.

Ex:-if we define datajpa-starter ,spring boot will provide persistence layer


features.

Ex:-if we define security-starter,spring boot will secure our application

..etc.

Note:- in spring boot we no need to download Tomcat server externally


separate like we do in advance java .here spring boot provide embedded
server.
->How to create spring boot project?

We can create spring boot project in two ways.

o spring initlizer website(start.spring.io)


o using IDE like STS(spring tool suit) recommended

spring initlizer website

->you need to go to browser and search https://start.spring.io/ you will get

->now just provide necessary information for your project like group,artefact
id,package name ..etc we already know about this in spring core.

->add required dependency if needed.

->click on generate button and your project get downloaded

->now you just need to open any IDE in our case (STS) and import it by clicking
on existing maven project .
By spring spring-tool-suit (STS)
->click on new then select spring starter project.

->provide all the information of project like name,artifact id,group,version,etc

->select dependency which required .

->at last finish.


->click on finish done.

Note:-STS Ide will internally connect with ‘start.spring.io’ website only to


create boot application.

Folder structure spring boot


->when we create spring boot project then bydefault we get one predefined
class called ProjectNameApplication.java inside src/main/java
/packagename..

->@SpringBootApplication annotation is equals to 3 annotations

->@SpringBootConfiguration annotation represent start class as


configuration class.
->@EnableAutoConfiguration annotation will enable auto-configuration
features in spring boot.

->@ComponentScan annotation is used to identify spring beans available in


the application.

Note:- as we know @SpringBootApplication annotation contains


@ComponentScan also which means IOC will scan and create bean/object for
all the component classes.

Note:-IOC will first search bean in base package and then sub-packages .if bean
is available in these 2 places then IOC will create bean. If bean is present in any
other separate package then IOC will not scan those beans until and unless we
not specify .
->but if we want that spring will scan different package also then we need to
override @ComponentScan() with basepackage parameter ,so that our IOC can
now able to scan all the packages specify there.

->now lets move ahead. We already understand lots of annotation in spring


core let see it again with some new annotation.

@Component:-as we already know to represent any java class as spring bean


we will use @Component annotations.

@Service:-to represent java class as spring bean which contains some


business logic we use @Service. This represent class as bean only but main
difference is that we write business logic in that class .any class where we write
business logic is nothing but service only right so we use this annotation.
@Repository:-to represent java class as spring bean which contains
persistence logic (related to DB operation) we will use @Repository
annotation. This @Repository provide beans but in addition internally it have
some extra feature due to which it able to handle DB related exceptions. Thats
the reason we use @Repository for DAO classes .

@Controller:-it represent a class as a Controller class,in web application to


handle incoming requests we will use @Controller annotation over our
controller class. Ex:- used in MVC

@RestController:- To develop distributed application we need to develop Rest


Controller (api and all) in that scenario we use @RestController we will see it
later..

We have also learnt about DI and autowiring in spring core section ..

@Qualifier: if there is more than 1 bean with same class type, using
@Qualifier we can match the bean id to be injected .@Qualifier is placed along
with @Autowired

@Primary: If we can declare @Primary in any of the @Bean/@Component,


then by default the bean with @Primary gets injected if there is a conflict in
autowiring of the beans with same class type provided there is no @Qualifier
matching present

->we already learnt about these annotation in spring core which will be used in
spring boot also..

Spring banner
->when we run spring boot application we can see that spring logo is printing
on the console that spring logo is nothing but banner.

->we can also customize spring boot banner by creating banner.txt file under
src/main/resources

->if you want banner in same style then you can generate ASCII text and keep
it in banner.txt file.
->we have 3 modes for spring boot banner

o off
o log
o console

off :- means banner will not be printed

log:- means banner will be in log file (if we use logging)

console:- banner will print on console (by default mode)

Now to configure banner modes we need to define it on


application.properties file
Ex:- spring.main.banner-mode=off

Runner in spring boot


->runner are used to execute any logic only one time once boot application
got started.means if you want to execute to perform any task which should run
only one time when execution starts then you go for runner.

->In spring boot we have 2 types of Runners

o ApplicationRunner
o CommandLineRunner

Note:- These ApplicationRunner and CommandLineRunner are Functional


Interface (functional interface is an interface which contains only one abstract
method)

->to use runner just you need to implements these runner Interface to you
classes where you need to implement .

->and write the logic what you want


Difference between both
->ApplicationRunner run() method taking ApplicationArgument object as a
parameter .

->CommandLineRunner run() method taking String[] as a parameter.

Usecase:-

->we can write cache logic on runner run() method means load data to cache
only once when application started.

->send any email or notification once our application get started.


->to store some common data like admin role and all when application get
started etc.

Spring Data JPA


->Data JPA is used to develop persistence layer in our application

->persistence layer used to communicate with database.

In Java Framworks we already have some technologies to make a persistence


layer like JDBC Api , Spring JDBC , hibernate framework , spring Orm.

->if we talk about JDBC developer need to take care about everything like
developer need to create connection, prepare statement for queries ,fire
queries using inbuilt methods, then at last close connection.

->spring JDBC built on top of jdbc only and it reduces lot of developer efforts
by taking care of db connections and db exceptions.. we just need to use it.

->above both api deals with data in text format

->To represent our application data in form of object we will go for ORM
framework like hibernate.

->by using hibernate we can develop persistence logic.

->In hibernate developer needs to takecare of session-factory , session,


transcation..etc.

->developer need to write lot of boilerplate code ,developer need to create


mapping file then configuration file etc for each entity.

->to overcome this Spring ORM came into picture by providing abstraction
layer for hibernate. Spring Orm provide predefined Classes to execute
methods directly but still there is some limitation. predefined methods
redundant issue may come.
->To overcome this problem Spring Data Jpa came into picture.

->spring Data Jpa providing ready-made methods to perform CRUD


operations . Which means we no need to write methods for CRUD operations
because Data Jpa provide for us.

->spring Data JPA provides ready made methods to perform CRUD


operations. Means developer no need to write methods to perform CRUD
operation it is taken care by Data Jpa.

->Data Jpa is used to developed persistence layer in our applications.

->by using Data Jpa it is very easy and clear to implement persistence layer.

->Data Jpa is auto configured and self logic implemented for CRUD operation.

->Data Jpa provides “Embedded Database Support” . means database


provided in application itself. Ex like h2.

->we can use this embedded database for temporary purpose.

->These embedded database are used in both development and testing


purpose but not for production.

->spring boot also supports both sql and No-sql database also.

->Data Jpa supports Easy Connection Pooling concept( auto-config).

->Data Jpa Supports Cache Management (Auto Config).

->Data Jpa has provided Repository Interfaces in package


“org.springframework.data.repository”.
Steps to Create first program using Data JPA

Step1. Create database in your Mysql database (in ourcase we are using
Mysql).

Step2:-create spring boot application with below dependencies.

o Datajpa-starter
o Jdbc driver (in my case mysql if you are using Oracle then use that)

Step3:-create Entity class with following annotations.


There are lots of annotation related to entity class provided by JPA define
according to your requirement.

@Entity:-it is a class level annotations, it can be used to declare a class as an


Entity class.

@Table(name=”tablename”):-it is a class level annotation, it is used to


configuretable name for the entity class. Where “name” attribute is used to
provide table name. And also used to map our class with db table name.

@Id:-it is filed level annotation . it is used to declare a property as a ID. And it


represent the field mapped with primary column in table.

@column(name=”columnname”):- it is used to provide database table column


name.what ever name you provide it will create column with that name and
map with it.

Note:- if in database table name and our entity class name is same then
@Table is optional.

Note:- if database column name and entity class field name is same then
@Column is optional.

Step4:-create Repository interface for Entity class.


Data Jpa provide 2 Interface to create Repository

o CrudRepository
o JpaRespository

CRUD Repository

->first create one interface and extends this repository .


We can able to use all method specified in Crud Repository.

Step5:configure datasource in application.properties file.

Step6:- call the repository method and test it by save data in db as off now we
are calling it from main class in future we will call it from service.

Save(obj):- this save method is from crudRepository(I) which is used to


perform save or update operation.

=>if primary key value is Null or not exist in DB then perform insert
operation,else if record is already available then update operation.

Note:-It is optional to write @Repository annotation for our repository


interface because when we have defined data-jpa starter in POM.xml file then
it will scan our project and it will identify JPA repository and it will provide
implementation for those repository. Save() is also called upsert() method.
So far we have done:-

->we developed one application using data JPA.

->we configure data-jpa starter in POM.xml.

->we have created one Entity class and used following annotations like

@Table,@Column,@Id,@Entity.

->we have created one interface and extends it with CrudRepository to make
Repo Layer.

Note:-for CrudRepository data Jpa will implement our interface using proxy
design pattern.

Let see following methods by Crudrepository.

Save(T obj):-to insert / update one record into table.

saveAll(Iterable obj):-to insert/update multiple record into table.

findById(id):-to reterive record using primary key.

findAllById(Iterabale<ID> ids):-To reterive records using multiple primary


keys.

findAll():- To reterive all records from the table.

Exists(id):- To checks presence of record in the table.

Count():-To check total records count in the table.

deleteById(id):-To delete record based on primary key.

deleteAllById(Iterable id):-To delete records based on multiple primary key.

delete(obj):-to delete record based on entity object.

deleteAll() :-To delete All records from table.


Note:- spring.jpa.hibernate.ddl-auto=create
->from above table will create automatically and every time new table will create. if you set it update
then it will update to existing table if table already present otherwise create and update it always.

->above diagram shows example of few methods we have used to perform crud
operation.

->we can create repository using by CrudRepository or by JpaRepostiory

->JpaRepository having additional features like Pagination , Sorting and


QueryByExample (QBE).
we recommends to use JpaRepository because it contains all the feature of
CrudRepository as well as some addition feature also.

->JpaRepository also used to perform sorting.

It is used to retrieve records based on sorting order.


Ascending order

Descending order
Jpa is used for Pagination

Query by Example (QBE)

->it is used to reterive records based on conditions just for filter kind of thing.

->as off now we have seen CrudRepository as well as JPARepository and few
methods like save(),findAll(),findById,delete(),deleteAll(),deleteById() etc.

->Note:- take entity id in Wrapper class format like (Integer,Long..etc) to get


proper result in Query by example
->now these methods are ok to deal with normal conditions but in real time
different-different scenario comes to deal with that data-jpa provides facility
to create custom method .

->we can create custom methods like findByXXx()..

->Spring Data internally generates a query based on method written in


Repository by developer.

findByXXX ( ) methods
-> findByXXX ( ) methods are used to construct the query based on method name in the
repository

-> We need to write findByXXX ( ) method using entity class property name (variable)

Note: Method name is very important here because based on method name
only jpa will construct the query and it will execute that query.

In simple word we need to use findBy.........


->as off now we have seen about custome method provided by Data-Jpa.

Now let’s see Custom Queries in Data JPA


-> Custom Query means we can write the query and we can ask data
jpa to execute our query.
-> We can write custom queries in 2 ways
o Native SQL (plain sql queries)
o HQL (Hibernate Query Language)
Native Sql queries
->In native style Sql queries will use table names and columns
directly in the query.
->native Sql queries are database dependent .
->database dependent means one DB sql syntax may not supported
by other DB .
->Native sql queries is not recommended because if we change our
database in future then we need to change our sql querries syntax
according to that database. As well as we need to again test
everything it will consume lot of time and efforts .
->To Overcome this Native Sql problem ,hibernate introduced its own
query language that is called HQL.
->HQL stands for hibernate query language.
->HQL querries are database in-dependent queries.
->internally HQL converted to Sql only using dialect .
->for every database hibernate have dialect classes.
->HQL we will prepare queries by using POJO/entity class name and
their properties.
->HQL queries syntax looks similar to SQL only but instead of table
name and column name we use entity class name and
property(variable) name.

To execute custom queries we will use @Query annotation.


Timestamping in Data Jpa
->When we insert or update a record it is very important to track when that
record get inserted or when that record get updated. so to track this it is highly
recommended to maintain columns in database related to insert and update
recorde like

Created_date

Updated_date

->Created_date column will represent when that record got inserted into
table.

-> UPDATED_DATE column will represent when that record got updated in
the table.

These column will help developer for analysis of insertion and updation in
future.

Ex:- provide all customer details register on last month.

->In Hibernate we have TimeStamping concept to insert created_date &


updated_date values.

@CreationTimeStamp

@UpdateTimestamp.

Ex:-
Generators
-> Generators are used to generate the value for primary key columns in the
database.

->As we all already discussed in our database portion about primary key ,what
is primary key,use of primary key and etc.

->as we already know Primary key is Unique and Not null.

->To represent primary key we use @Id annotation.

->in real time when we develop application we should not ask end user to
enter value for primary key because end users may enter duplicate value
which may create ambiguity in our records.

->So we will use Generators to generate primary key column values with in the
application.

->we use @GeneratedValue annotation to apply generator for primary key


value.
@Id

@GeneratedValue

@Column(name = "student_id")

-> When we insert record into table, sid value will be generated through
@GeneratedValue annotation

Note: If we use oracle database then it will use hibernate_sequence by default


to get primary key column value (select hibernate_sequence.nextval from
dual)

Note: hibernate_sequence is the default sequence created by hibernate in


oracle database.

Note: MySQL Database will not support for sequences. MySQL DB will use Auto
Increment to generate the value for Primary key Columns

Some more annotations related to JPA

@OneToOne:-used to define one-to-one mapping between two entity beans.

@OneToMany:-used to define one – to – many unidirectional entity mapping.


@ManyToMany:-it represent many –to-many relationship between two
entites. It is typically used to map a collection of child entites to a collection of
parent entites.

Transcation
->To understand transcation let understand this example
->we want to transfer money from source account to target account.
->To transfer money we need to perform two logic
1)we need to deduct money from source account
2)we need to credit /add money to target account.
->if both operation happen successfully means transaction is
succesfull.
But if we transfer the amount and amount deducted from source
account successfully but failed to credit the amount in target
account then our Transcation got Failed.
->we also discussed about Atomicity . that either All or None.
Means if amount failed to credit to target account then that amount
should come back source account this is called rollback.
->in Data JPA when we perform Non-Select Operation then
Transaction will be committed by default.
->it is not automatically rollback.
->if we want to rollback the transcation then we should use
@Transactional annotation.
Ex:-
Repos

Spring Web MVC


->Spring Web Mvc is one module available in Spring framework.

->in plain spring developer need to take care lot of boilerplate code but spring
boot reduces lot of work because of “Auto-Configuration” functionality.

->using MVC module we can develop 2 types of applications

o Web Application
o Distributed Application

->The application which can be access from browser is called web


application.
Ex:- facebook,twitter,IRCTC,MakeMyTrip..etc

->generally Web application are used for C2B business which means customer
to business model.

Ex:- users < ------------------ > IRCTC

->The application which is communicating with other application are


called distributed application.
->Distibuted Applications are used for Business To Business
Communication. Which means one application will not directly
contact with customer instead of it communicate with another
application .
Ex:- makeMyTrip is communicating with IRCTC
Ex:- goibibo is communicating with any airline portal for flight booking
what is the need of distributed application ?
->just imagine if you want to develop weather forcast application or
you need to start your own business which help full to book train
ticket. If you do every thing from zero like to establish whole
infrastructure as well as whole communication system then lot of
budget will required. lot of money power,man power needed.
So this not smart way to make money , the smart way is the
companies who already have big infrastructure as well as man-power
and whole eco-system . just contact with them and pay amount to
them so that your application can communicate with their application
.so you are doing here B2B business.
Ex:- phonepe,googlepay,paytm are one application using which you
can transfer money very easily so you are using these application but
internally these application are communicating with banking
application ,if suppose paytm will not communicate with banking
application then paytm need to build it’s own infrastructure and
needed lot of man-power and moneypower .better option is to deal
with banks and give some percentage to them and use their
application.
In simple you can say instead of re-developing everything from
scratch we can reuse service of one –application in another
application.

To make Distributed application we have 2 approches


o SOAP based webservices (legacy very old almost dead now)
o Rest Full Webservices (trending and latest)
->when we are developing Distributed application then 2
terminology we mostly see.
o Provider
o Consumer
Provider:-The application which is providing business services to
other applications is called as provider.
Consumer:-The application which is accessing business services from
another application is called as Consumer.
->distributed application are language and platform independent
which means application developed on different-different language
using different –different platform can communicate each other these
feature is also called “intereoperable”.

Spring Web MVC Architecture


Dispatcher Servlet(FrontController):-dispatcher servlet is a
predefined servlet class which will act as a front controller. It is
responsible to perform Pre-Processing and Post-Processing of a
request.
Handler Mapper:-it is used to identify which request should be
processed by which controller method in our application.
Controller:- it is used to handle a request .
ModelAndView:-modelandview is a predefined class and model holds
data in key-value format and view refers logical view name.
->ViewResolver is used to identify physical location of view files
available in the project.
->view is used to render Model Data in the view component.
->mvc working in springboot in simple words:-request first comes to
the dispatcher servlet which is front-controller provided by spring
boot. Dispatcher servlet pre-process this incoming request (by
identidying headers, body and data of request) and after pre-
processing it pass request to handler mapper. Now handlermapper
role come into picture and it identify which controller method need to
invoke .so after identidy that method it passes that request again back
to dispatcher servlet . and now dispatcher servlet execute that
controller methods. Now controller method will return
ModelandView Object to dispatcher servlet. Now dispatcher servlet
passes controller over ViewResolver and view resolver find the view
file location in our project and finally all model data rendered in view
and send response to client.
->Building First web application using spring web mvc
->To create web project spring boot provides starter i.e “web-starter”
dependency.

->web-starter provides embedded-server(bydefault tomcat).

->Embedded servers are built-in servers which are used to run our
application. Like in advance java here we no need to install apache tomcat
separate and add to project.

->add “tomcat-embed-jasper’ dependency in POM.xml file ,

Note:- when we are using JSP as a view then only this jasper dependency
needed otherwise this step is not required (because springboot not provide
support of JSP so we need this ).

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

Note:- if we not add this jasper dependency and we are trying to using JSP file
then if we send request to our controller it will download that file instead of
displaying response.

->as we know in JSP we can write in normal JSP scriplet tag as well as JSTL also.
So we need to add one more dependency if we want to use JSTL .

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>
->select “war” instead of jar . if you select war then springboot will provide
webapp folder. Otherwise you need to create it manually.

->we need to use @Controller annotation over our Controller class to make it
controller.

-> Bind controller class method to HTTP GET Request using @GetMapping
annotation.

->create view file inside webapp location.

Step1:-

Step2

Select java version and war, and select starter-web.


Step3
Step4:-

Step5:- add these to application.properties file

Step6:-
Using Lombok
->as we know we need to create getter and setters and if required
then zero args constructor and parametrized constructor. But to avoid
all these writing part we can use Lombok also,so that Lombok will take
care of getter,setter,constructor and all , just we need to use Lombok
annotations.

->using Lombok is not mandatory it’s depend on developer


requirement. Just to reduce code we can use it.
Sending Data From UI to Controller
->We can send data from UI to Controller in 3 ways.
o Query Params
o Path Params
o Request Body
Note:-Query Params & PathParams will represent data in URL.

Query Paramteres.
->Query parameter represent data in key-value format.
->Query parameter will present only at end of the URL.
->Query Parameter will start with ‘?’.
->TO use multiple query parameter we can use ‘&’ as a separator.
->To read query parameters from URL we will use @RequestParam
annotations.

Ex:-
Path Parameters
->Path parameter is also used to send data to server in URL.

->path params will represent data directly.(no key-value format)

->path parameter can be present any where in the URL ,not necessary to keep
at end you can place anywhere.

->to represent data in URL using path param we need to use placeholder.{}

Note:- to read path parameter from URL we need to use @PathVariable


annotations.
Note:-Path Parameter & Query Parameter will represent data in URL.
->we can send only text data in URL not supported for binary data.
->in both the cases data is displaying in URL, not recommended for
sensitive data.ex(password,pin,code,id..etc).
->there is some data limit in URL depends on browser.
->if we want to send any simple and text format data then we go for
these both concept.
Note:- as we seen both query param and path param are used to send
data in URL. So question arise where to use which.
In general if we want to retrieve multiple records then go for Query
Param.
And if we want to retrieve unique records then go for Path Param.
Example related to Form based application in MVC
->as we know form is an very essential part of any web applications
->Form are used to collect data from users and send it to server.
->spring web-MVC provides “form-tag-library” to simplify forms
development.

->this spring web-mvc tag lib contains lots of tag which help to deal
with form data.
Ex:
<form:form/>

<form:input/>

<form:password/>

<form:select/>

<form:option/> & <form:options/>

<form:radioButton/> & <form:radioButtons/>

<form:checkbox/> & <form:checkBoxes/>

<form:hidden/>

<form:error/>
->To bind java object to form we will use ‘modelAttribute’ attribute.

->To bind Form-fileds(controls) to Object variable we use ‘Path’ attribute.

Task1:- collecting data from form and store to db(mysql)

->we will follow this architect , here we are making service layer direct
class , we can also achieve loose cupling by using interface also if
required.
We can also use H2 database , H2 database is embedded database
provided by spring boot.
->to use H2 database we need to add H2 dependecy.
->Note:- H2 database is for POC(proof of concept) means just for
temporary purpose to test your concept as you shutdown your server
you will loose everything)
<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

</dependency>

->configure H2 datasource properties in application.properties file


H2 db console

Model interface
->like we have seen how spring mvc uses ModelAndView object and
how we are adding data and view name to it, like wise
->we have one Model Interface and we can send data from
Controller to UI using Model Object.
->this also represent data in key-value pair.
->we can write controller using ‘Model’ interface like below to send
data from Controller to UI.
->in Model we no need to set view name by using any method .
directly return String your view name it is automatically understood.

->as off now we have seen spring MVC .that either you use
ModelAndView class or Model Interface they both return view file
name and dispatcher servlet give this view file name to View Resolver
to get location.
->means what ever string you return dispatcher thinks it like a view
file name and it passes it to View Resolver and then it is identified by
view resolver.
->but if you want to send response directly without any view File.
Then we need to bypass the step of ViewResolver means dispatcher
servlet directly give response no need to pass it to viewResolver.
->So to send response directly to User without any View File then we
need to use annotation called @ResponseBody.

->here we have used @ResponseBody so here response will go


directly no any View file like JSP and all.
Thymleaf
->we used JSP as a presentation technology in our web mvc project.
->JSP can’t be executed in browser directly means when request
comes to JSP then internally JSP will be converted to Servlet and
Servlet will send response to browser.
->so When we use JSP for presentation logic the burden will increase
on server because every JSP should converted into Servlet and
number of conversion may increase.
->To overcome that Thymeleaf come into picture. And it is used for
presentation logic.
->Thymleaf is a template engine that can be used in HTML directly.
-> as compared with JSP Thymeleaf is fast .
->Thymleaf provides dynamic nature to our HTML page.
-> to use thymeleaf in spring boot we need to add thymeleaf-starter.
->create thymeleaf template in Src/main/resources/templates
folder.
->file name with .html extension.
Note: No need to configure view resolver because Spring Boot will detect
theymeleaf template files and will process them.

Thymeleaf is a modern server-side Java template engine for both web and
standalone environments, capable of processing HTML, XML, JavaScript, CSS,
and even plain text.

Thymeleaf Engine
Thymeleaf Engine will parse Thymeleaf Template. It uses Java model data to replace the
positions marked on the Thymeleaf Template to create a new text in the HTML page.

 Well, in web applications, the Thymeleaf is processed on the server.


 Results are included in the HTML and returned to the browser.
Steps to create Thymeleaf project

Step1.

Step2

Step3
Step4.create controller

Step5: create html file in template depending upon what view name you are
returning means here i am returning “about” .

So file name must be about.html.


Spring Boot + Thymeleaf + Form validations – Example
We have one dependency for Form validation we need to add that so that we
can perfrom Form Validations.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
difference b/w application.properties & application.yml
->When we create spring boot application, by default project provides
application.properties files under src/main/resources folder.

->all the project configuration we do inside application.properties file.

->application.properties file supports configuration details in key-value


format.

Ex:-

->application.properties file will represent data in sequential manner.


.YML files

->it is an alternative of application.properties file.

->YML stands for yet another markup language.

->YML Files will represent data in hierarchical manner.

->YML files is more readable then .properties files.

Note:- be careful of spaces while writing .YML files .give proper spaces .

->we can also convert Our application.properties files to application.Yml files


Note:- application.properties file will support only java where as yml files are
supported by multiple programming languages.

->In profiles concept , for every profile we need to create separate


application.properties file.

->but in case of YML , single yml file is sufficient to deal with all profiles.

Profiles:- In real time application are developed and tested in various


environments like dev,uat,local..etc.

->so we need to make separate configuration files for every environment if we


are using .properties file like

Application.properties,application-dev.properties,application-
uat.properties,application-prod.properties.

Same we can also defined in .YML approach. In .YML we have two option
either you can create separate file for different profile or in same file also you
can manage.

->we need to define profile in base file that spring need to use which
environment file for configuration .
->if we not use any profile concept then we need to change our configuration
file every time dependents on environment but it is very bad approach to
change our configuration file in real time because if by mistake something
went wrong then it may cause big issue.

Ex:- suppose in real time we have 3 environemnt dev,test,prod environment


and for every environment we have separate database for our application for
production we have production db config which connects with database which
store production data.

For test we have separate database config which related with database which
stores test data used for testing.

Similarly we have separate database in local system which used for


development purpose so we have separate config related to that dev config.

So if we change every time then it become headic for developer as well as


chances of getting issue is high.

So to overcome this we can use Profiles concepts.

->bydefault spring boot loads application.properties file i.e base file.

->so in base file you need to specify which environment specific file project
should used.
What are RESTFul Services ?
->Restful Services are used to develop “Distributed Application”. Which is
independent of any programming language as we already discussed above
distributed languages.

->as we already know if one application is communicating with another


application then we call it as distributed application.

->distributed applications are intereoperable means irrespective of the


platform and language if application are communicating then we call them as
interoperable applications.

Why we should use Distributed Application?


->As we already discuss what is distributed application and it’s use case.

->we have already discussed about B2B how companies are doing B2B using
distributed applications.

->we already know what is producer application and what is consumer


application.

->The application which is providing business services to other appilcations is


called as Provider
->The application which is consuming business services from other applications
is called as Consumer.

->application can exchange data over network in XML,JSON format

->JSON format is trending in market as well all latest tech stack supports JSON
format.

Now days JSON is ruling over market.

->lets see something related to XML approach first.

XML
->XML stands for Extensible Markup Language.

->it is governed by w3C.

->XML is also tag based language. Which represent data in elements like

Ex:- <id>111</id>

->elements tag are paired means contains start tag and end tags.

-> Every xml will start with prolog

<?xml version="1.0" encoding="UTF-8">

-> Prolog represents processing instructions

Note : Every XML should contain only one root element

<?xml version="1.0" encoding="UTF-8">


-> In the above xml we have 2 types of elements

1) Simple Element

2) Compound Element

What is Simple Element?

The element which represents data directley is called as Simple Element

Ex: <id>111</id>

What is Compound Element?

The Element which represents child elements is called as Compound Element.

<student>

<id>111</id>

</student>

-> We can use attributes also in the xml

ex: <book-name type="java">Spring</book-name>

-> Attributes are used to provide supplement information for elements

-> XML is intereoperable and we already discussed about intereoperablity.

-> SOAP Webservices will support only xml format for exchanging data

-> RESTful services supports for xml and some other formats also like json.
->so to transfer/exchange data from one app to another app we need to
convert one type format to respective type Object.

Lets see how to convert XML to java Object and java Object to XML.
Marshalling & Un-Marshalling
->Marshalling & Un-Marshalling are called Runtime Operation.
->The process of converting java Object into XML is called as
Marshalling.
->The process of converting XML into java Object is called as Un-
Marshalling.
Note: These operations will happen when the application is running

Note: To perform Runtime operations Binding classes are mandatory.

Working with JAX-B


-> JAX-B api & its implementations are part of JDK only (directley we can use it)

-> From Java 11 onwards JAX-B removed from JDK, we have to add JAX-B
dependency in pom.xml.

Marshalling program using jaxb api.

->in program we are just focusing on marshalling (java obj-- > XML).

->create one java class.

->add jaxb dependency to POM.xml

->depends on spring version jaxb may differ.

->then in main class create Marshall object and just pass object and file name
with xml extension it will create file .
In spring 2.x
un-marshalling (xml to java object)

Here we using unmarshal() methods. Which again converts xml into object.

JSON
->JSON stands for javascript object Notation.

->JSON format is universal format to exchange data over a network.

->JSON is intereoperable (platform independent & language independent).

->as compared to XML ,JSON is light weight (it occupies less memory).

->JSON represent data into key-value format.

->JSON object always starts with { and ends with }.

->with in { and } , JSON object contains multiple elements where each elements
represent properties.

->elements are present in key:value structure.


->each key:value pair is separated by comma(,).

->The values corresponding to JSON keys can be String , Integer , boolean ,


JSONobject or array.

->JSON array can contains array or list of String,numbers,json object etc.

->JSON array starts with [ and ] .

-> In Java we don't have direct support to work with JSON data

-> We have third party apis to work with JSON data in java applications

o Jackson Api
o Gson Api
-> Using above third party apis we can convert Java Object to Json and Json to
Java Object.

-> Converting Java Object into JSON data is called as Serialiation.

-> Converting JSON data to Java Object is called as De-Serialization.


-> Normal POJO classes we can use to perform Serializaion and De-Serialization with
JACKSON api

Working with Jackson API

Java object to json


Add maven dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

Create pojo class

Create main logic


If we want json file then use

Now JSON to JAVA

->we use readValue(jsonfile,object)

->there are lots of method but this is most imp concept.


Working with GSON API
->In gson api we have a predefined class called 'gson'.

->Gson class contains below methods

o toJson ( ) ==> To convert java obj to json format


o fromJson ( ) ==> To convert json to java obj

Java object to JSON string

However, the toJson method in Gson doesn't have an overload that directly
takes a File as a parameter.

You should first convert the object to a JSON string using toJson, and then
write that string to the file.
Now JSON to java Object

->above code we have pass json string directly. We can also pass
FileReader as an parameter see below
HTTP Protocol
->HTTP stands for hyper text transfer protocol.

->Http is a kind of medium or we can say mediator protocol between client &
server.

->in client server-architecture . client will send HTTP request to server and
server will process that request and send HTTP response back to client.

->Http is stateless protocol.

->stateless means it can’t remember the conversation happened between


client & server.

HTTP Methods
->there are several method which help us to deal with http
request/response
o GET:-it is used to get response from the server.
o POST:-it is used to send data to server(used in creation purpose)
o PUT:-it is used to update record at server.
o DELETE:-it is used to delete the record at server.
->When we deal with REST API and all then we need to bind Our
controller end methods with these HTTP protocol methods.
Ex:-
GET -----> @GetMapping
POST -----> @PostMapping
PUT-----> @PutMapping
DELETE----> @DeleteMapping.
Request/response contains two major parts i.e
o Header (it contains metadata)
o Body(it contains payload (business data))
Some HTTP Status Code
-> Response Header will contains HTTP Status Code. When we send response.
->actually this status code give information that how our request get
processed .every thing fine or not.
1xx - INFORMATIONAL

2xx - OK (Success)

3xx - Redirectional (www.sunmicrosystem.com -> www.oracle.com)

4xx - Client Error ex:- 404

5xx - Server Error

Note: Http Status Codes will play very important in distributed applications
development
Note: POST, PUT and DELETE Methods having request body. GET method don't
have request body. Because get is used to send data to server and rest of them
used to send data.

Building First REST API using Spring Boot


Let us know some more before building first api.

-> ResponseEntity is a predefined class available in Spring Web MVC

-> Using ResponseEntity class we can construct Response with body and status
code.

Syn:- new ResponseEntity<>(body, HttpStatus);

Note: REST API Methods should have Unique URL Patterns otherwise we will
get ambiguity problem. We need to make sure our methods should be
identified uniquely.

->we will use @RestController because @RestController method will


return response directly.
Note: No concept of returning "view file names" in RestController.

@Controller + @ResponseBody = @RestController


-> @GetMapping annotation is used to bind RestController method to
HTTP GET Req.
-> HTTP GET request is used to get data from server

-> HTTP GET request will not have body

-> To send (small piece of data like ld,key or etc) data to server in GET request
we will use below 2 options

1) QueryParams

2) PathParams

These two we already discussed before.

Note: In Spring Boot, we no need to write JAX-B and Jackson


logics directly because Spring Boot will take care of that.
Note: Spring Boot internally uses HttpMessageConverters to deal
with XML and JSON.

->Now days we uses JSON format to exchange data over applications


First Rest API using SpringBoot.
1) Create Spring Starter Application with below dependencies

- spring-boot-starter-web

- spring-boot-devtools
2) Create RestController class using @RestController annotation

3) Write methods in RestController and bind them to HTTP Protocol method

4) Run the application and test it

Note: To test REST API functionality we will use POSTMAN software


Dealing with XML response.
->first add JaxB API for XML ..because bydefault it gives JSON response no need
any configuration for JSON but for XML we need to use @XmlRootElement
In header we need to pass accep :application/xml.
Note-1 : In @GetMapping annotation, "produces" attribute represents in which formats
our REST API method can provide response to clients

Note-2 : Client will send request with "Accept" header.

Ex : Accept = "application/json"

Based on "Accept" header REST API will send response to client in that format.
Internally "HTTP Msg Converters" will be used to convert the object data into
client understandable format.

produces & Accept


=> "produces" attribute represents in which formats REST API method can
provide response

=> "Accept" header represents in which format client expecting response from
REST API.

Dealing with XML & JSON data in request body


-> To send sensitive data and huge amount of data clients will use Request
Body.

-> "Content-Type" header represents in which format client sending data in


Request Body.

-> "consumes" represents in which formats REST API method can take input
data.

->if we send request with some huge data then we use


@RequestBody annotation . this enabling automatic deserialization of
the inbound HttpRequest body onto a Java object. Spring automatically
deserializes the JSON into a Java type,
Task:- develope full Rest API using controller,interface with loosly
coupled diagram with mysql database.
In Realtime, Producer Application Development team will provide
documentation to Client Side Development in 2 ways
o Swagger
o PDF document

Swagger
->Swagger is third party api

->Swagger is used to generate documentation for Rest API.

->Swagger provides attractive UI to test REST API.

->To use Swagger in our project we need to add some dependencies to our
project.
Swagger implementation for spring 2.xx version.

For 2.xx version add these dependencies.


<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>

-> After adding dependency, we need to create SwaggerConfig class. In this


class we will specify for which classes it has to generate documentation.
In latest springboot 3.xx swagger
->in this we need to use OPEN-API
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-
ui</artifactId>
<version>2.0.3</version>
</dependency>

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.15</version>
</dependency>

Just add this dependency ,here no need to create object class of


Docket and all just add this dependency and access URL

URL:- localhost:8080/swagger-ui.html
As we know earlier that we can create distributed application
for B2B . In which one application which provide services is
producer application . and another application which
consumes that services is called consumer application.
-> The application which is accessing REST API is called as REST
CLIENT.
-> In Spring Boot we can develop REST Client in 2 ways

o RestTemplate (Synchronus client) - Outdated


o WebClient ( Sync + Async client ) – Trending

-> RestTemplate is a predefined class, it is part of "spring-boot-starter-web"


dependency. It is used to create synchronous client .

-> WebClient is a interface, it is part of "spring-boot-starter-webflux"


dependency.

Note:-using webclient we can make synchronous and asynchronus client.

Synchrnonus
->after sending a request it will wait for the response to proceed further.
Usecase of synchronus client:- see above diagram in this our client app is
developed to show weather info on the basis of zip code.

->so we have one another app which provide zipcode on the bases of city
name and we have one another app which provide weather info on the basis
of zipcode.

->so we can use here synchronus kind of thing because until we don’t have
zipcode no use to hit weather info provider api.

->so after sending the request for zipcode wait for response until response not
come execution will not move further.

asynchronous
program to handle multiple tasks simultaneously rather than executing
them one after the other. Means execution will not wait for response of
other task .

->here no api are related then why to wait for response of one api . so in this case we can
go with asynchronus.
Ex:- RESTTEMPLATE

Demo application for asynchronus client (webclient).


->to create asynchronus client .we need to add one more
dependency call ‘spring reactive web’
->we will try to communicate with our old app train app.

Run this app in different port server.port=9999.


Because our train app is running at 8080.
So for handlind asynchronous response we create handler method so when ever response
comes we execute this method. Our execution will move forward it will not wait ..

Exception Handling
-> Exception means an unexpected and unwanted situation occuring the
program execution is called as Exception as we already discussed in core java.

->when exception occurs then program will be terminated abnormally (stops


in middle).

->as a developer we need to takecare of that our program must terminate


normally instead of abnormally.

-> as we already know in java we have 5 keywords to handle exception


o try
o catch
o throw
o throws
o final

->as we know code which have chance of exception we put inside try block.

->catch is used to handle that exception.

->throw keyword is used to re-throw the exception.

->throws keyword is used to ignore the exception.

->final block is used to write clean up activites (closing files, closing


connection..etc).

Exception handling in REST API


->In Rest API we can handle Exception handle in two ways.

o Controller Based Handling.


o Global Exception Handling.

->Controller Based Handling means writing Exception Handler methods in


Controller class. That exception handler works only for the controller class
exception .

->To handle exception of any class in project level then we go for Global
Exception Handling. We use @RestControllerAdvice annotation for Global
Exception handling.

->we use @ExceptionHandler annotation over handler method either in


controller based or global based.

Controlle based exception handling ex


->Global Exception handling Ex

->in Controller based handling we create handler methods but that handler
method is specific upto that handler only means if we have 5 controllers then
separately we need to maintain handler method in each controller .code
redundancy may occur . suppose for NullPointerException we create separate
handler in first controller as well as in second controller separate .Our code will
work fine but handler method duplication occur.

TO overcome that limitation we can use GLOBAL EXCEPTION HANDLING.

->in Global handling technique we create separate class which is dedicated for
handling Exception occurs in any where in our application. Inside this class only
we define different-different handler method based on exception.

->we need to use @RestControllerAdvice annotation over this global class.

Global rest controller


********************MICROSERVICES**********************

Before understanding microservices lets understand about monolith.

What is Monolith Architecture?

->The term ‘monolith’ is used to refer to applications that are designed as a


single unit. Which means all the functionality is bundled together .all the logic
like UI logic, business logic , DB logic ..etc are bundled as a single unit.

->We package our application as jar/war to deploye into server .

->as monolith application contains all the functionality it will become heavy
jar/war .

Advantage of Monolith
->simple to develop

-> Everything available at one place.

->easy to understand.

->less configuration.

->less resources required (ex:- man power,infra)

Dis-Advantage of Monolithic.

->Difficult to maintain.

->single point of failure:-if any error occur in project then entire project may get failed /down .

->less Scalabiltiy:-because monolithic architecture software is tightly coupled, it is hard to scale.

->dependencies between functionalites because of tightly couple.


To overcome the problems of Monolith, Microservices architecture came into
market.

->Microservice is not a programming language.

->Microservice is not a framework.

->Microservice is an architectural design pattern.

->Microservices design pattern help to develop application functionality with


loosely coupling.

->In Microservices architecture we don’t develop all the functionalities in


single project. We divide project functionalities into several REST API’s.

->which means one REST API project is One Microservice.

->for every major functionalities we create one microservice which fulfill that
functionality.

->Microservices is not related to Only Java. Microservice pattern can be


followed by different project development languages.

Advantages:-

->Easy to maintain because clear and cut separate code base.

->Faster development. Different-different microservices are developed by


team members simultanesouly.
->Technology Independent:- different microservice can build on different
programming languages and then they can communicate with each other.
There is no dependency over languages.

->high Scalability:-each microservice can be scaled independently without


downtime.

->No –single point failure:- a failure in one microservice does not affect other
microservice. This is also called Resiliency.

->independent component can be tested independently.

Disadvantages of Microservices

->resource consuming and need high man-power and infra.

->complicated deployment:-Once you have developed each microservices,


then they need to be integrated and deployed Is critical task.

->high budget required .business wise not recommended for small scale
projects .

**********Microservices Architecture**************
-> We don't have any fixed architecture for Microservices

-> People are customizing microservices architecture according to their requirement

-> Most of the projects will use below components in Microservices Architecture..

1) Service Registry (Eureka Server)

2) Services (REST APIs)

3) Interservice Communication (FeginClient)

4) API Gateway (Zuul Proxy)


Service Registry

->Service Registry acts as database of services availablein the project.

->it provides the details of all the services (microservices) which are
registered with Service registry.

->we can easily identified how many services available in the project.

->we can identify how many instances available for each service.

->we can use “Eureka Server” as service registry.

->Eureka server is provided by “Spring Cloud Netflix” library.

Services
->Services means REST API/Microservice.

->service contain business logic.

->In project ,some services will interact with 3rd party rest API.

(if one service communicate with any 3rd party service then we call it external
service communication . we perform it using by RestTemplate , WebClient).
->In the project, some services will interact with another service with in
project then we call it inter-service communication. To perform it we use fient-
client .

->To distribute the load. We can run one service with multiple instances.

Note:-we will register every service with service registry.

API Gateway
->API Gateway is used to manage our backend api’s of the project.

->API Gateway acts as mediator between end users and backend api’s.

->API Gateway can filter logic to decide request processing.

->API gateway will contain Routing logic (which request should go to which
rest api’s).

->API gateway also registered with service registry.

Small example:-

Create one service registry app


->just create one small app and add eureka server dependency.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Configure property file

Note:- bydefault port for eureka is 8761. Which means all the eureka client will
automatically detects this service registry and register .

Note:- in starter class add @EnableEurekaServer annotation.

Now just access this eureka dashboard. As off now no client service is registered in it we
need to configure that services and run them also .

Hit:- http:localhost:8761
Create services which need to register with eureka service registry.

->we need to add eureka discovery client dependency on client.

-> we need to use @EnableDiscoveryClient annotation in starter class.

->configure properties.xml file.

NOTE:- in microservice pattern giver every service port different because


bydefault port is 8080.

NOTE:- also give different service application name in properties file.

Service 1:

Service 2
What if we change eurka service registry port other then 8761 ?
->suppose now our eureka is running on port 9090 then. In this case our services will
unable to automatically regestired it self then we need to add these config to properties
files in every eureka client service.

eureka:

client:

serviceUrl:

defaultZone: http://localhost:9090/eureka

Microservices inter-communication (feign client)

To see its example we need to create


1.service registry project (because feign client use it)

2.more then one microservice to achieve inter –communication.


Service registry

Song data app(service 1)

->this is normal service one

Service 2 (this service inter-communicate with service one)


Q)why we use feign-client , if we have RestTemplate and WebClient for communication ?

->in these both we need to defined endpoint in hardcode way. What ever end-point we
define it hit that api and communicate. Which is fine . but to achieve load balancing these
both will not full fill requirement.

->in load balancing one api is running on multiple instances. So feign-client is designed in
such a way that it pick api name from service registry and internally it perform load-
balancing if one api is running in multiple instances. It using round-robin approach.

->eueka ,feign-client all these are cloud based concept.

**********API Gateway******************
->as we discussed API Gateway will act as a mediator between client request and
backend.

->Api gateway will provide single entry point to access our backend api.

->we need to register this gateway to service registry.

-> In Api Gateway we will write mainley below 2 types of logics

1) Filters

2) Routing

Filters:-Filters are used to execute some logic before request processing and
after request processing.

Routing:-routing is used to configure which request should go to which rest-


api.

-> In Spring Cloud we have 2 options to create API Gateway

o Zuul Proxy (older version not supported by latest spring boot v)


o Cloud Gateway (latest)

API –Gateway example using cloud gateway.


1)create one api gateway service.
-> web-stater

-> eureka-client

-> cloud-gateway

-> devtools
-> We can validate client given token in the request using Filter for security
purpose

-> We can write request and response tracking logic in Filter

-> Filters are used to manipulate request & response of our application

-> Any cross-cutting logics like security, logging, moniroing can be


implemented using Filters.
Actuator
->Actuators will provide various information relation to our web api like

->it provide health of our application .

->how many beans loaded by our application.

->what config props loaded by our application.

->what is heap info of our application.

->how many threads runnings in our application.

->how many URL mappings available in our application.

->To Configure actuators in our applications spring boot provided below starter

->Note:- by default actuator exposes only health endpoint . to expose all endpoint we
need to configure one property in properties file.

->config these property in properties file.

->make controller (I have create just simple controller to demonstrate actuators).


->run project and visit:- http://localhost:8080/actuator

->you will get all end points now from here you can see any info regarding app.

->In Actuator we have a special endpoint called shutdown.

->This /shutdown endpoint is binded to HTTP POST request.

->using this endpoint we can stop our application.

->to use this we need to enable configuration in properties file.


Spring Boot Admin Server and Admin Client
->spring boot admin is a web application. Used for managing and monitoring spring boot
application. Here each application is considered as a client and register to admin server.
Behind the scene magic is done by actuator.

Create project for admin service

Working with Admin-Server

1) Create Boot application with admin-server dependency (select it while


creating the project)

2) Configure @EnableAdminServer annotation at start class

3) Run the boot application

4) Access application URL in browser (We can see Admin Server UI)
Working with Admin-Client

1) Create Spring Boot application with below dependecies

a) starter-web

b) starter-actuator

c) admin-starter-client

d) devtools
3) Create Rest Controller with required methods

4) Run the appplication (It will register in Admin Server)

Circuit Breaker
-> Circuit Breaker is a design pattern in Microservices

-> Circuit Breaker is used to implement fault-tolerance systems

-> Fault-tolerance systems are also called as resillence systems

-> Fault-tolerance system means when main logic is failed to execute then we
should execute fallback logic to process client request.

Usecase example
get data from redis

if redis logic is failing then we should get data from database

Note: If redis logic is failing for 3 requests continuosly then execute db logic for
30 mins. After 30 mins re-try for redis logic execution if it is working then
execute redis logic only. If 3 re-try executions failed with reds then execute db
logic for next 30 mins.
POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.6</version> //or use 2.5.4
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>circuitapp</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>

<spring.cloud-version>2020.0.3</spring.cloud-version>
<spring-cloud-starter-netflix-hystrix.version>2.2.8.RELEASE</spring-cloud-starter-netflix-
hystrix.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>${spring-cloud-starter-netflix-hystrix.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<builder>paketobuildpacks/builder-jammy-base:latest</builder>
</image>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

</project>

Starter class
@SpringBootApplication
@EnableHystrix
public class CircuitappApplication {

public static void main(String[] args) {


SpringApplication.run(CircuitappApplication.class, args);
}

Controller
@RestController
public class MyController {

@GetMapping("/data")
@HystrixCommand(fallbackMethod = "getdb", commandProperties = {
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
@HystrixProperty(name = "circuitBreaker.enabled", value = "true") })
public String getData() {
System.out.println("getting data from redish.............");
int nextInt = new Random().nextInt(10);
if (nextInt <= 10) {
System.out.println("---------------- "+nextInt);
throw new RuntimeException("redish down..");
}

return "data from redish "+nextInt;


}

public String getdb() {


System.out.println("getting data from database.............");
return "data from db";
} }
Sleuth & Zipkin
-> Zipkin is a very efficient tool for distributed tracing in the microservices ecosystem. Distributed
tracing, in general, is the latency measurement of each component in a distributed transaction where
multiple microservices are invoked to serve a single business usecase.

Sleuth is another tool from the Spring cloud family. It is used to generate the trace id, span id and
add this information to the service calls in the headers and MDC, so that It can be used by tools
like Zipkin and ELK etc. to store, index and process log files.

-> If we add Sleuth dependency in REST API then it will add span-id and trace-id for log
messages

-> For every request once span-id will be generated by Sleuth

-> If one request is processing multiple REST API then Sleuth will use same span-id for
REST APIs to generate log message.

-> Trace-id is specific to one REST API.

-> By using span-id and trace-id we can understand which REST api has taken more time
process request.

-> To monitor span-id and trace-id details we will use ZipKin server.

-> Zipkin server is providing user interface (UI) to monitor all the details.

Note: The REST APIs which are having sleuth dependency should register with Zipkin
server.

Note: By using Sleuth and Zipkin we achieve Distributed Log Tracing.

Ex: In Spring 2.xx we use sleuth

Controller
@RestController
public class MyController {

Logger logger = LoggerFactory.getLogger(MyController.class);

@GetMapping(value = "/all")
public String getAll() {
logger.info(" **** getAll execution started ****");
String msg = "Welcome to codeminetech...!!";
logger.info(" **** getAll execution ended ****");
return msg;
}
}
Pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zipkidemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<builder>paketobuildpacks/builder-jammy-base:latest</builder>
</image>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

</project>

Spring boot 3.xx (we not use sleuth we use zipkin with following config)

Controller
@RestController
public class MyController {

Logger logger = LoggerFactory.getLogger(MyController.class);

@GetMapping(value = "/wel")
public String Wel() {
logger.info(" **** wel() execution started ****");
String msg = "Welcome to codeminetech...!!";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://localhost:8080/msg", String.class);

logger.info(" **** wel() execution ended ****");


return result;
}

properties
server.port=9090

# Zipkin configuration
spring.zipkin.base-url=http://127.0.0.1:9411/
spring.sleuth.sampler.probability=10
spring.application.name=welcome

poM

->when you select zipkin dependency in springboot 3.xx then these 3 dependecies will
come.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>

<dependency>
<groupId>io.zipkin.reporter2</groupId>
<artifactId>zipkin-reporter-brave</artifactId>
</dependency>

->just run zipkin server from cmd and run our project.

SONAR QUBE
->Code quality and Security are vital to the success of any organization . in organization
both junior and senior developer work together in a project in a team. So junior developer
can write code which is not up to mark . then senior developer need to do code review . so
that quality code will go to live production environment.

->To maintain the code standard and quality code review must done frequently.

->when we talk about code review then Sonar qube tool comes into picture. Sona qube is
a code quality assurance tool that perform in-depth code analysis and generates an
analysis report to ensure code reliability.

->Sonarqube is an automatic code review tool.

->sonarqube supports for 29 programming languages.

->sonarqube will identify bugs,vulnerabilities,code smells,duplicate code blocks…etc.

Install sonarqube

->download sonarqube software from internet

->start sonar server by executing StartSonar.bat file.

->by default sonar server 9000 port number .

->add following plugins in POM.XML in plugins sections


<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.4.0.905</version></plugin>
POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.8</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sonarqubedemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>

<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.4.0.905</version>
</plugin>

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<builder>paketobuildpacks/builder-jammy-base:latest</builder>
</image>
</configuration>
</plugin>
</plugins>
</build>
</project>
->make controller and all
->start sonarqube server

->now run this and hit http://localhost:9000/

-> Do Maven build of project with package goal

mvn clean package

-> For project do maven build with below goal To Do Code Review

mvn sonar:sonar

-> After maven build completed, check sonar server dashboard.

You might also like