Introduction to Spring Boot
What is Spring Boot Ovsecr
Spring Boot is basically an extension of the Spring framework
Spring Boot Framework is not implemented from the scratch by
The Spring Team,
It eliminated the boilerplate configurations and some tedious
development steps required for setting up a Spring application.
Spring Boot uses completely new development model to make
Java Development very easy
Embedded HTTP XML cbean>
Spring Boot Spring Framework Servers Configuration or
(Tomcat, Jetty) @ Configuration
Problems with spring framework (orem
= The core feature of Spring framework is dependency injection.
Spring alsoe provides great integration with other frameworks,
like Hibernate. Spring provides a few frameworks of its own - for
example, Spring MVC for developing web applications and REST
API.
If you look at any Spring-based application, such as a Spring MVC
application, many configurations in xml file.
[Link]. [Link]:
jews/
amen" suFFix">
Problems with spring framework Ossecr
= Configuring DispatcherServiet in deplyment descriptor
= Configuring data-source as well as transaction manager
"org. springfranework. orn. pa. LocalContatnerEntityanagerFacts
titynanagerFactory">
rsistenceunithane” values"hsgl_pu” />
source’ referdatasource® />
efetentitymanagervactory=
datasource™ />
rty nanes"dataseurce’ refs
n- driven transaction-managers" transact ionkanager
Features of Spring Boot Oxvecr
= Itis very easy to develop Spring Based applications with Java or
Groovy(language).
It reduces lots of development time and increases productivity.
It avoids writing lots of boilerplate Code, Annotations and XML
Configuration.
Itis very easy to integrate Spring Boot Application with its Spring
Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security
ete.
It follows “Opinionated Defaults Configuration” Approach to reduce
Developer effort.
It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop
and test our web applications very easily.
It provides lots of plugins to develop and test Spring Boot Applications
very easily using Build Tools like Maven and Gradle
It provides lots of plugins to work with embedded and in-memory
Databases very easily.Advantage (o)7)20
= Inreal-time spring applications we need writing many XML
configurations, server setting, adding dependencies...etc. But with
spring Boot we can avoid all these boilerplate code, writing XML
configurations and annotations.
Spring Boot comes with inbuilt server, we no longer have to use
any external servers like Tomcat, Glass-fish or anything else, so
don’t need to deploy WAR files
The intelligent auto-configuration attempts to auto-configure
your application based on what dependencies you added. It is
contextually aware and smart.
Spring Boot provides starter dependencies which can be used to
manage dependencies for jar files. spring-boot-starter-web can
be used for developing web application. It avoids writing multiple
dependencies.
Goals of Spring Boot [ora
= To avoid XML Configuration completely
= To avoid defining more Annotation Configuration(It combined
some existing Spring Framework Annotations to a simple and
single Annotation)
To avoid writing lots of import statements
To provide some defaults to quick start new projects within no
time.
= To provide Opinionated Development approach.
The disadvantages... Osvecr
= The main disadvantage is, it will be little tough to migrate existing
spring enterprise applications to Spring Boot.
Large deployment files that result from unused dependencies
Its inability to build large, monolithic applications (although it
works extremely well for developing microservices)Tien) clea) ol (ol 01g
= Let us learn Spring Boot Hello World application using Eclipse and
Maven. Steps to be followed are :
1. Create File > New > Maven Project
2 Select ‘create a simple project’ checkbox and check default
workspace location for storing the project
3. In this window provide Group ID(it’s a package name) and
Artifact ID(Project Name) and click on Finish button
a Amaven project gets created in your workspace with the
following structure 4 3 SpringBootHelloWorld
& stc/mainjave
rc/main/resources
@ sic/testjova
® src/test/resources
Ba JRE System Library (125E-1.5}
& sc
© target
BB pomam!
Talento (oem
= Please Note : We are going to change Java version little later
5. Now we will add Spring Boot related stuff in [Link]
= Add spring-boot-starter-parent in [Link]
Td>com. object<
>SpringBoo!
0. 1-SNAPSHOT<
>first simple demo
>[Link]
Id>spring-boot-starter-parent:
1.5.6, RELEASE< >Simple Example Ovsect
+ Spring-boot-starter-parent is an existing project given by spring team which
contains Spring Boot supporting configuration data
+ It will not download any jar files
*
tag in [Link] allows to manage the following things for multiple
child projects and modules:
‘+ Configuration - Java Version and Other Properties
‘+ Depedency Management - Version of dependencies
‘+ Default Plugin Configuration
6. Create a simple bean class annotated with @Component
@component
public class Test
{
public string tostring()
t
return "String reprenetation of Test bean";
)
?
7. Write following code for finding list of beans that get created
@springBootApplication
ublic class SimplespringBootApplication (
Pee ijublic seatic void main(sering{] exge) {
ApplicationContext ctx =
[Link] ([Link], args);
/#test t = [Link] (Test .class!
System. [Link]([Link]()
7
String [] beans = [Link] ();
for (String beanName : beans)
System. [Link] (beanName) ;
@SpringBootApplication annotation, means this is the starting point
for our Spring Boot application
8. Add java version in properties element
9. Right click on the application > Maven > Update Project. Observe
the directory structure of the project; It will create maven
dependencies folder which will include all the supporting jar files
and java version even will be modified to 1.
10. Finally, right click on the application > Run As > Java ApplicationSimple example for web developme
= Inthe dependencies, add spring-boot-starter-web for web
module.
>[Link]<
s>spring-boot-starter-web {
//save, fetch, update, delete
Steps for developing REST API Ossecr
= Step 5: Creating Service Classes
= Service classes will encapsulate business logic like performaing
some calculations, filtering the records etc which will take the
help of repository to deal with the database.
import [Link];
import [Link];
@service
public class ContactService {
Gautowized
ContactRepository crepo;
public List getall ()
t
return [Link] ();
= Step 6: Creating a Controller
= Controller classes are used for accepting the request and
providing the request processing logic.Steps for developing REST API Ossecr
= Controller class is annotated with @RestController, which tells
Spring Boot to consider this class as REST controller and register
@RequestMapping paths inside it to respond to the HTTP
requests. _
Ghe: rolle:
public class ContactController {
@autowired
ContactService cservice;
@cettapping("/allcons")
public List getall()
{
return [Link] ();
}
= Step 7: Compile, Build and Run
8080 is the default port that Spring Boot runs in. To run the
application, run the application as java application. Check
messages with console.
Steps for developing REST API Ossecr
= Step 8: Testing the Spring Boot REST APIs
= Spring Boot REST API is now up and running on
[Link]
= Tosend an HTTP GET request, go to [Link]
from your browser or using postman tool and check the response
received in the form of JSON.
“name” :"Jane”@Componentscan annotation (oT 01g
= Right now RestController is created in the same package as that
of Main Application
= So Spring boot will automatically scan all the components under
that package at the time of starting the application
= If we create RestController in different package, we need to tell
Spring Boot to scan this component explicitly otherwise
application will generate 404 error
= Add @Componentscan annotation for the main class
public a! pplication {
public static void main(String{] args) (
[Link]([Link], «
’
Customized methods in repository (ol 701g
= Rules to define customized query methods in repository.
= Rule 1—The name of the query method must start with findBy or
getBy or queryBy or countBy or readBy prefix. The findBy is
mostly used by the developer. for example.
* public List findByName(String name);
* Note: name is the name of the property in entity class
Rule 2 — The first character of field name should capital letter.
Although if we write the first character of the field in small then it
will work but we should use camelcase for the method name.
* public List findByname(String name); // valid but
should be avoided
Rule 3 — While using findBy or getBy or queryBy or countBy or
readBy the character B must be in capital letter, else we will get
an exception while deployment.
-* public List findbyName(String name); //invalidCustomized methods in repository Olam
= Rules 4—We can write the query method using multiple fields
using predefined keywords(eg. And, Or etc) but these keywords
are case sensitive. We must use “And” instead of “and”.
+ public List findByNameAndRollNumber(String name, String
roliNumber); //valid
+ public List findByNameandRollNumber(String name, String
roliNumber); //invalid
Rule 5 — We can write the query method if we want to restrict the
number of records by directly providing the number as the digit in
method name. We need to add the First or the Top keyword
before the by and after find. for example :
* public List findFirst3ByName(String name);
Using @Query annotation O/T Lom
= Writing JPQL using Spring Data Jpa @Query.
GQuery("select s from Student s where [Link] = 21")
List getStudents (String name);
Writing the Named Parameter @Query.
aH Co TNE EIN aa SETS STRSTR)
ListeStudent> FindByName(@Param(“name") String name);
Write query method using JPA @NamedQuery and
@NamedNativeQuery.
entity
@NamedQuery(name = "[Link]”, query = “select s from Student s where
[Link] = 21")
public class Student {
{fields and getter setter
Create method in the repository using the same name as that of
the query with one parameterExecuting DML queries OT op
/JexecuteUpdate
@Modi fying
@query("update Contact set fname = 71 where email = 22")
public int updateName (string fnm, string email);
= DML queries even can be executed using for the custom methods
in the repository. For executing it in a transaction, use
@Modifying annotation above the method and @[Link]
annotation above the repository.
= The @Modifying annotation is used for INSERT, UPDATE, DELETE,
and even DDL queries. When @Transactional annotation is
declared at the class level, it applies as a default to all methods of
the declaring class and its subclasses. It helps in commiting the
updations to the database.
Calling procedures from repository Obsyecr
//preparecall
@Procedure (name="getName", outputParameterName = "nm")
public String getName(int cid);
= In this case, repository method is annotated with @Procedure
where “getName” is the name of the procedure and name of the
output parameter is “nm” which is returned by the method as in
the form of string.