Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Spring Boot

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 99

Spring Boot

What is Spring Boot

• Spring – Framework
• Boot – BootStrap
• Bootstrap spring application from the scratch

2
What is Spring Boot?

• Official definition (spring.io):

• Spring Boot makes it easy to create stand-


alone, production-grade Spring based
applications that you can "just run“
• Developed by Pivotal Team
• Used to create micro services

3
What is micro service?

• An architecture that allows the developers to


develop and deploy services independently.
• Each service has its own process and this
achieves the lightweight model to support
business applications.

4
Problems with Spring
• Huge framework
• Multiple setup steps (Spring can do many
things)
• Multiple configuration steps
• Multiple build and deploy steps
• Handling dependency management is a
difficult task when the project grows
• Spring boot will abstract out these steps
• So that we can focus only on business logic

5
Spring Boot - Characteristics

• Opinionated
• Start with something (Good starting point)
• Tweak it later based on requirements
• Convention over configuration (Look at 80%
use cases)
• Stand alone (Just run, no looking for servlet
container & configure etc.)
• Production ready
6
Spring Boot - Characteristics

• You can get started with minimum


configurations without the need for an entire
Spring configuration setup.

7
Spring Boot - Advantages

• Easy to understand and develop spring


applications
• Increases productivity
• Reduces the development time

8
Spring Boot – Goals

• To avoid complex XML configuration in


Spring
• To develop a production ready Spring
applications in an easier way
• To reduce the development time and run
the application independently
• Offer an easier way of getting started with
the application

9
Spring Boot – Set up
• - JAVA 8 JDK
• - Spring STS (Spring Tool Suite)
• - flavor of Eclipse
• - tweaked to work with spring boot
• - Download from https://spring.io/tools3/sts/all
• - Java dependencies:
• Use Maven as dependency management
tool

10
Download STS and install
https://spring.io/tools3/sts/all/

11
Managing Dependencies

• In Enterprise applications, we depend on


other libraries (.jar files)
• Downloading and keeping in the classpath
– difficult step, we need to manage such
dependencies
• For Spring Boot, we will be using MAVEN
as dependency management tool

12
Java Dependencies
• Normally, we go to websites
• Download required jar files
• Add to the classpath

13
Java Dependencies with
Maven

14
Create starter project with
Maven
• We can use Maven to create starter project
• Starter project: Template (using archetype)
• Archetype is a Maven project templating toolkit.
An archetype is defined as an original pattern or
model from which all other things of the same
kind are made.
• So, we will be using this concept to create spring
boot application too

15
Creating spring boot application
There are multiple ways:
1. Create a simple maven project, turn it into Spring
Boot application
2. Using online Spring Intializr
3. Using Spring Boot CLI with groovy scripts
4. Using Spring Starter Project in STS

16
Creating a maven project
• Create a Maven Project and make it as a child of
spring-boot-starter-parent, has opinionated setup
(default configuration for instance, JDK).
• Add in pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
• <parent> is the maven concept (Inheritance)

17
Do you know?
• <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
• This version would go ahead and pull all the pre-set versions
of required jar files
• We don’t need to worry about the versions of individual jar
files
• This is called as “Bill Of Materials”, which is approved by
Spring Boot

18
Include meta-dependency
• Next, we want to create web application (think about
all dependent .jar files)
• Add in pom.xml and update maven project:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
• This starter project has all the dependency list (.jar)
so we don’t need to list out individual jar files
19
Create a Java class with main
method
• Name: CustomerAPIApp
• Add main() method
• This is going to bootstrap the application

20
Run the project Java Application
• Right click this class
• Run as Java application
• This is just a dummy project
• It has nothing
• Let’s add the controller class now
• Look at the console:

21
Look at the console

22
Changing the container’s port no
• If any other application listens to port number 8080
• You would get a failure message
• In this case, we need to change the port number of the
tomcat container
• Just add “application.properties” with the following
one line to /src/main/resources folder and restart the
application
– server.port = 8088
• Now, tomcat will be started on port no. 8088

23
Starting Spring Boot
The magic line - SpringApplication.run()
1. Sets up default configuration (addresses 80% use
cases) – convention over configuration
2. Starts Spring application context (Spring Container)
- Creates a contains - runtime environment
- starts when spring application starts
3. Performs class path scan
- Marking your class with annotation
- Looking at the annotation, it will be creating
component accordingly
4. Starts tomcat server
24
The magic of annotation
• The spring framework scans all the classes for
the annotations:
• @controller – the class will be treated as
controller class
• @service – the class will be treated as service
class
• @SpringBootApplication – the class will be
treated as spring boot application
• Spring infers all this from annotations

25
Access the URL

• http://localhost:8088/
• It would display the error page, since there is no
explicit mapping, so you would get a fall back
page

26
Why Spring Boot is stand-alone?
• Did you add Tomcat container?
• All you needed was to just invoke the run
method on SpringApplication class
• You didn’t need to download any .jar files
• Running a web application is just like running
a stand-alone Java program from a main
method.

27
Add a controller class
• Let’s map a URL to a controller class
• So, when we access the URL, let’s display
some message on the browser
• Let’s start with a simple example 
• http://localhost:8080/hi  URL (‘hi’ is the
request)
• We should display “Hi to Spring Boot”

28
Add Controller class
• Controller class is a Java class
• It has @RestController annotation at class level
• It has @RequestMapping annotation at method level
• The web layer in Spring Boot application leverages
spring-mvc framework which is a child project of
entire spring framework.

29
Restart the application
• Click the Relaunch icon from STS
• Open the browser
• Type:
– http://localhost:8080/hi
– It should print "Hi to Spring Boot"

30
Modularize your app
• For better modularity, you can place this class in
another package “com.ofss.mycontroller”

31
Spring Boot Starters

• Dependency management is a difficult task for


big projects.
• Spring Boot resolves this problem by providing a
set of dependencies for developers
convenience.
• For instance, if you want to use Spring and JPA
for database access, it is sufficient if you
include spring-boot-starter-data-jpa dependency in
your project (pom.xml)

32
Spring Boot Starters

• Note that all Spring Boot starters follow the


same naming pattern spring-boot-starter- *,
where * indicates that it is a type of the
application.
• Examples:
– spring-boot-starter-web
– spring-boot-starter-actuator
– spring-boot-starter-security
– spring-boot-starter-thymeleaf
• More can be found at https://docs.spring.io/spring-
boot/docs/current/reference/html/using-boot-build-systems.html
33
Case Study – Customer
Management System
• Imagine, we are going to build REST API using
Spring Boot for a Chartered Accountant
• The CA maintains different customers’ data
• The main entities are:
– CUSTOMER
– BANK
– PORTFOLIO
• I am going to walk through this problem
throughout this course and show the
implementation
34
Returning list objects
• Building a REST API:
– http://localhost:8088/customers
– It should return a list of customer objects
• We need a Customer class with properties like
firstName, phoneNumber, emailId
• Create some good bunch of Customer objects
(with values) and add it to Collection List
• Return this list from the controller class
• Implement this and restart the application

35
Returning objects
• When the URL is fired, it would return an array of
JSON objects

36
Verify in postman

37
@EnableAutoConfiguration

• You could also use this annotation in the


main class
• But, you need to add @ComponenScan
annotation also
• If you add @SpringBootApplication, you
don’t need to add any other annotation

38
@EnableAutoConfiguration

• In this case, your main class would look


like this:

39
Customers API – How to design?
• When designing / developing REST API, you need to think
about:
• We need to identify the resources:
1. Resources Deal with NOUNS or ENTITIES
1. Recall: CUSTOMER, BANK, PORTFOLIO
2. In terms of Customers API, Customer is the resource
3. The consumers can access these resources using different HTTP
methods:
1. GET – for reading
2. POST – for creating / inserting
3. DELETE – for removing
4. PUT – for updating completely
5. PATCH – for updating partially

40
Designing Customers API
• Resources:
– Customer
– Bank
– Portfolio

41
Designing Customers API
• GET /customers Gets all customers
– We already developed this
• Here, the root URL is the name of the resource but in
plural
• We could also have query parameters and path
parameters
• Similarly:
– GET / banks Gets all bank details
– GET / portfolio Gets all portfolio details (list of
investments held by a customer)

42
Designing Customers API
• GET /customers/id – Gets a customer
• POST /customers – Creates a new
Customer
– We need to send the POST BODY
• PUT /customers/id – Updates a customer
• POST body contains the information to be updated.
• DELETE /customers/id – Deletes a specific customers

43
Introducing service classes/layer
• In any application, service class / layer is
a place where other components seek the
services
• For instance, the controller ask service
class to give a list of customers, give the
database connection, open a specific file
etc.
• In Spring framework, service class is a
normal class with @service annotation
44
Create a service class
• Service class name: CustomerService
• Annotate this class with @service
annotation
• package: com.ofss.service
• Define a private variable “allCustomers”
which contains a List of Customer objects
• Method name: getAllCustomers()
– This method returns the variable “allCustomers”

45
Create a service class

46
Create a service class
• Service class is singleton in Spring
• When the spring application starts, it
creates only one instance of the class
which is marked with @service
annotation
• We are going to use this pre-instantiated
service class object in controller class
using DI mechanism (@Autowired)

47
Modify the controller class now

48
Implementing /customers/name API
Getting a single resource
• Let’s now implement the GET method for
the URL /customers/name
• This API should return the customer
details for the given customer name
• The URL:
– GET method for /customers/name

49
Add a controller method
• Add the following method in the controller class:
@RequestMapping("/customers/{name}")  This is called PATH parameter
public Customer getCustomer(@PathVariable String name)
{
return customerService.getCustomer(name);
}
Path Variable and method parameter names could be different:
@RequestMapping("/customers/{name}")  This is called PATH parameter
public Customer getCustomer(@PathVariable(“name” String
customerName)
{
return customerService.getCustomer(name);
}

50
Add a service method
Add the following in CustomerService class
public Customer getCustomer(String name)
{
Customer cust=null;
for (Customer c:allCustomers)
{
if (c.getFirstName().equals(name))
cust=c;
}
return cust;
}

51
Invoke the API
Now, from the browser, give the following URL:

http://localhost:8088/customers/Guru  This is called PATH parameter

You should see the details about the customer “Guru”

{"firstName":"Guru","lastName":"Murthy","phoneNumber":9
731801675,"emailId":"java.guru@yahoo.com"}

Check the same in POSTMAN

52
Implementing POST method
Adding a single resource
• How about adding a new Customer to our
existing list.
• In this we must use “POST” method for
the URL: /customers
• But, we need to send whole bunch of
details (firstname, lastname,
phonenumber, emailid)
• For this we must prepare JSON request
body 53
Implementing POST method
Add a service method
public void addCustomer(Customer cust)
{
allCustomers.add(cust);
// add new customer to our existing list
}

54
Creating a new Customer using this API?
In POSTMAN tool:
• Give the URL: http://localhost:8088/customers
• Select POST method
• In request body, select raw:
Add the following JSON object:
• {
• "firstName": "Raju",
• "lastName": "Rama",
• "phoneNumber": 123456243,
• "emailId": "raju.rama@yahoo.com"
• }
In the Headers, create one key:
• Content-Type and give the value application/json
55
Creating a new Customer using this API
Verification:

• Invoke the URL http://localhost:8088/customers


In GET method
• You should see the changes

56
HANDS-ON
Implement the API to delete a customer

URL: http://localhost:8088/customers/Guru
Method type: DELETE

This should remove the customer with the firstName =


“Guru”

57
Spring Initializr
• This is another way of creating Spring Boot application
• Go to the website: https://start.spring.io/
• Fill up some required details
• Your spring boot application is ready
• Download as .zip file and extract local folder
• In STS, import this .pom as maven project
• Just run the program
• Your application will just run 
• Just take care of the tomcat port #

58
Spring Boot CLI
• This is the command line interface
• You can create spring boot application using this
• This is not very popular
• Just use this for demo purpose
• Go to this web site
• https://
docs.spring.io/spring-boot/docs/current/reference/html/g
etting-started-installing-spring-boot.html
• Download and extract the following file into local folder
• spring-boot-cli-2.1.2.RELEASE-bin.zip

59
Test Spring Boot CLI
• Spring Boot CLI uses groovy script
• Groovy is another language like Java
• Go to the “bin” folder
• D:\spring-boot-cli-2.1.2.RELEASE-bin\spring-
2.1.2.RELEASE\bin
• Run “spring.bat” file
• It would give all the options
• Check the Spring Boot CLI version:
D:\groovy-scripts>spring.bat --version
Spring CLI v2.1.2.RELEASE
D:\groovy-scripts>
• We need to write controller class using groovy script

60
Write Controller in groovy script
• Spring Boot CLI uses groovy script
• Groovy is another language like Java
• Create a file helloctrl.groovy (extension is groovy)
• Write the following into it and save this file
@RestController
class helloctrl
{
@RequestMapping("/")
String hello()
{
"Hello Groovy"
}
}

61
Run the groovy script
• Change the port number of tomcat in spring.bat as
follows
set CLASSPATH=%SPRING_HOME%\lib\*"%JAVA_EXE%"
%JAVA_OPTS% -cp "%CLASSPATH%" -Dserver.port=8087
org.springframework.boot.loader.JarLauncher %CMD_LINE_ARGS%
• Run as following:
• D:\groovy-scripts>spring.bat run helloctrl.groovy
• Access this application in browser
• http://localhost:8087/
• Use this option for prototyping or creating simple applications

62
Groovy script in execution

63
Using STS IDE
Spring Starter Project
• Recall bootstrapping from spring initializr (https://
start.spring.io)
• Select File…New…Spring Starter Project and fill the
details

64
Using STS IDE
Spring Starter Project

65
Using STS IDE
Spring Starter Project
• Select next
• Select the Spring boot version
• Select the dependency
– Select Web in our case
• Select Select
• Select finish
• Right click project,
• run as “Spring Boot App”
• Or
• Right click on main class,
• run as “Java Application”

66
Dependency Injection

• Spring is very famous for its DI concept


• IoC – Inversion of Control
• Dependency Injection is of two types:
– Constructor based
– Setter based
• Examples:
– @Autowired

67
Customizing Spring Boot
application
• Add application.properties file in resource folder
• Add “server.port=8091” to change the default
port number of tomcat (8080 to 8091)

68
Customizing Spring Boot
application
• Add application.properties file in resource folder
• Add “debug=true” to enable the debug

69
How to find the property
names?
• The official documentation contains all property
names
• https://
docs.spring.io/spring-boot/docs/current/reference/html/co
mmon-application-properties.html

70
Spring Boot Database

Spring JDBC

71
Spring JDBC
with Spring Boot
• We need data source
• We need to build JdbcTemplate using DS
• We will be using methods defined in
JdbcTemplate and providing our SQL queries
• Spring Boot requires very minimal configuration
for this
• No need to explicitly define dependencies in
Beans.xml
• We will be using spring-boot-starter-jdbc

72
Spring JDBC
with Spring Boot
• We need data source
• We need to build JdbcTemplate using DS
• We will be using methods defined in
JdbcTemplate and providing our SQL queries
• Spring Boot requires very minimal configuration
for this
• No need to explicitly define dependencies in
Beans.xml
• We will be using spring-boot-starter-jdbc

73
Spring JDBC
with Spring Boot

74
Spring JDBC
with Spring Boot
• Let’s create a console based application for a
change
• So, bootstrap Spring application using File…
new…Spring Starter Project
• Your pom.xml should depend on:

75
Spring JDBC
with Spring Boot
• You would get an error in pom.xml saying oracle
• Missing artifact com.oracle:oracle:jar:11.2.0.2.0
• This means, that this particular .jar file is not
found in public maven repository due to licensing
issue
• You must download this file (ojdbc6.jar) from
oracle website – for version 11.2.0.2.0
• https://
www.oracle.com/technetwork/apps-tech/jdbc-11
2010-090769.html
76
Spring JDBC
with Spring Boot
• Go to the folder where you have downloaded
“ojdbc6.jar”
• Now, install this .jar file into local maven
repository by invoking the following command:
• mvn install:install-file -Dfile=ojdbc6.jar
-DgroupId=com.oracle -DartifactId=oracle
-Dversion=11.2.0.2.0 -Dpackaging=jar
-DgeneratePom=true This last parameter for generating a POM
will save you from pom.xml warnings

• You should get “BUILD SUCCESS” message


77
Spring JDBC
with Spring Boot
• You should see an entry in your local maven
repository:

78
Spring JDBC
with Spring Boot
• Provide all connection details of ORACLE DB in
application.properties
application.properties (resource folder)
• server.port=8091
• #oracle db settings
• spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
• spring.datasource.username=<<your-user-name>>
• spring.datasource.password=<<your-password>>
• spring.datasource.driver-class-
name=oracle.jdbc.OracleDriver

79
Spring JDBC
with Spring Boot
• Create the database table “employee” in ORACLE DB
create table employee(firstname varchar2(20) primary key,
lastname varchar2(20),
phonenumber number(10),
emailid varchar2(20));
• Make sure the table gets created
• If you select from this table, you would see zero records

80
Spring JDBC
with Spring Boot
• Let’s create EmployeeService interface

81
Spring JDBC
with Spring Boot
• Let’s implement EmployeeService interface

82
Spring JDBC
with Spring Boot
• Let’s create EmployeeDao interface

83
Spring JDBC
with Spring Boot
• Implement EmployeeDao interface

84
Spring JDBC
with Spring Boot
• Create and run the application as stand-alone

85
Spring Boot Database

Spring Data JPA

86
Spring Data JPA

• JPA - Java Persistence API


• Specification for ORM
• SQL Databases are called Relational
Databases(keys: primary & foreign keys)
• JDBC
• Class <-> Table (you need to do the mapping
yourself)
• ORM maps Classes to Tables

87
Spring Data JPA

• Spring Data JPA is a separate project


• It lets you to work with ORM tools even easier
• You don’t need to write any XML configuration
files
• This is going to be super easy
• Connecting to embedded Databases
• Connecting to external Databases

88
Spring Data JPA
Connecting to embedded
Databases (Apache Derby)

89
Spring Data JPA
Marking your POJO as @Entity & @Id

90
Spring Data JPA
Creating Data Service Class /
Creating a Spring Data JPA Repository

91
Spring Data JPA
Connecting to external Database
(ORACLE)
• From pom.xml:
– Remove the derby related dependency
– Add “oracle db” as dependency
<dependency>
<groupId>com.oracle</groupId>
<artifactId>oracle</artifactId>
<version>11.2.0.2.0</version>
</dependency>

92
Spring Data JPA
Connecting to external Database
(ORACLE)
• You would get an error in pom.xml saying oracle
• Missing artifact com.oracle:oracle:jar:11.2.0.2.0
• This means, that this particular .jar file is not
found in public maven repository due to licensing
issue
• You must download this file (ojdbc6.jar) from
oracle website – for version 11.2.0.2.0
• https://
www.oracle.com/technetwork/apps-tech/jdbc-11
2010-090769.html
93
Spring Data JPA
Connecting to external Database
(ORACLE)
• Go to the folder where you have downloaded
“ojdbc6.jar”
• Now, install this .jar file into local maven
repository by invoking the following command:
• mvn install:install-file -Dfile=ojdbc6.jar
-DgroupId=com.oracle -DartifactId=oracle
-Dversion=11.2.0.2.0 -Dpackaging=jar
-DgeneratePom=true This last parameter for generating a POM
will save you from pom.xml warnings

• You should get “BUILD SUCCESS” message


94
Spring Data JPA
Connecting to external Database
(ORACLE)
• You should see an entry in your local maven
repository:

95
Spring Data JPA
Connecting to external Database
(ORACLE)
• Provide all connection details of ORACLE DB in
application.properties
application.properties (resource folder)
• server.port=8091
• #oracle db settings
• spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
• spring.datasource.username=<<your-user-name>>
• spring.datasource.password=<<your-password>>
• spring.datasource.driver-class-
name=oracle.jdbc.OracleDriver

96
Spring Data JPA
Connecting to external Database
(ORACLE)
• Create the database table “customer” in ORACLE DB
• create table customer(FIRST_NAME VARCHAR2(10),
LAST_NAME VARCHAR2(10), PHONE_NUMBER
NUMBER(10), EMAIL_ID VARCHAR(10))
• Make sure the table gets created
• If you select from this table, you would see zero records

97
Spring Data JPA
Connecting to external Database
(ORACLE)
• Good news is:
– No change required in entity class (Customer)
– No change is required in controller class
– No change is required in service class
– No change is required in repository class
• Now, restart the application
• With postman client:
– Create some resources (records)
– View the resources
– Update resources
– Delete some resources

98
End of Spring Boot

99

You might also like