Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Spring Boot & Microservices - Day3

The document provides an overview of Spring Boot and Microservices, detailing prerequisites, software requirements, and key features of Spring Framework and Spring Boot. It explains the differences between traditional Spring applications and Spring Boot, including configuration methods and dependency injection. Additionally, it covers creating RESTful web services, using Spring Data JPA for database interactions, and outlines the architecture of a typical Spring Boot application.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Spring Boot & Microservices - Day3

The document provides an overview of Spring Boot and Microservices, detailing prerequisites, software requirements, and key features of Spring Framework and Spring Boot. It explains the differences between traditional Spring applications and Spring Boot, including configuration methods and dependency injection. Additionally, it covers creating RESTful web services, using Spring Data JPA for database interactions, and outlines the architecture of a typical Spring Boot application.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Spring Boot & Microservices

Pre-requisites
- Java
- Spring Framework
Software requirements
- JDK 8 or later
- Eclipse / STS
- MySQL
- Postman Client

Spring Framework helps to develop various types of applications


like desktop, mobile, web, cloud, it provides many features which
helps to ease the development process like
1. Design patterns
2. Type conversion
3. Exception Handling
4. Security
5. Transaction Management
6. Separating the application code & configurations
Spring Boot
- It simplifies developing applications using spring which are
ready to run
- It provides many non-functional features which are like
servers, external configurations
- It helps you to quickly to move from one environment to
another environment with very less configuration
- It doesn’t need any XML configuration files to configure the
application
- It takes care of automatically configuring the applications
based on the library you have in the project
Spring vs Spring Boot
Spring Spring Boot
It is a framework has many It is one of the spring farmwork
modules like spring core, mvc, module
rest, boot
Non-spring boot uses XML Spring Boot doesn’t need XML
configuration file to configure file, it configures everything
the object dependencies with annotation, @Component,
@Autowired
Non-Spring boot uses external Spring Boot provides
server, so that you need to embedded server
setup server explicitly
Non-Spring boot uses Spring Boot provides auto-
configurations that has to be configuration using the
explicitly specifies either in libraries it provides which are
XML or code called spring boot starters

Example: In Non-Spring boot datasource configuration is done as


below
<bean id = “datasource” class =
“org.springframework.DataSource”>
<property name = “username” value = “root” />
<property name = “password” value = “root1234” />
<property name = “url” value = “ip:port:databasename” />
<property name = “drirverClassName” value =
“someDriverClass” />
</bean>
Example: In Spring boot datasource configuration is done in
property files as below
Spring.datasource.username = root
Spring.datasource.password = root1234
Spring.datasource.url = ip:port:databasename
Spring.datasource.driverClassName = someDriverClass

How to configure dependency injection in non-spring boot


application in xml file
Suppose Object of B depends on object of A
class A { }
class B {
A obj; // object of B needs object of A // obj = new A();
}
XML Configuration:
<bean id = “x” class = “citibank.A”></bean>
<bean id = “y” class = “citibank.B”>
<property name = “obj” ref = “x” />
</bean>
Annotation configuration
@Component
class A {
}
@Component
class B {
@Autowired
A obj; // object of B needs object of A // obj = new A();
}

How can spring boot do configurations automatically


1. It needs some starter libraries provided by spring boot
starter
2. It needs one annotation @SpringBootApplication to scan all
the starter libraries
Ex:
1. Spring Boot Starter Web library
This library is scanned by @SpringBootApplication and
automatically configures the application to work in web
environment so that you don’t have to configure server,
front-controller and many other things
2. Spring Boot Starter Actuator
This library is scanned by @SpringBootApplication &
automatically configures the application to track in the
production environment with some endpoints like health,
status, metrics and many more
3. Spring Boot Starter Data Jpa
This library is scanned by @SpringBootApplication &
automatically configures the application to connect to the
database by using the configurations in the
application.properties, it means you don’t have to write the
code to connect to database

Spring boot project


1. We need to use Maven project – for library configuration
2. We need to setup right Java version
3. Spring provides one website where you can download the
project template : spring.io or spring initializr

Steps to create our first spring boot project


1. Goto spring initializr
2. Configure the project with name, libraries and etc
3. Download & Extract the project in your IDE

Libraries
1. Web
2. Devtools
How to run spring boot applications
1. From machine you can launch the application using IDE
2. You can create an executable jar file and run using java -jar
command

Important Points to remember while running jar


- If the base machine which is running the jar is having higher
java version compare to the java version packaged in the
project then you don’t have to set the path
- If the base machine java version is lower than the java
version used by the project then you must either upgrade
the java version of the base machine or downgrade the
project java version
- In Linux you must use export to set the path
- In Windows you must use set path command to set the java
version path.
Command used to run the jar file
java -jar filename.jar
The above command uses the port specified in
application.properties
java -jar filename.jar –-server.port = 9091
The above command overrides the server port
By default spring boot uses tomcat as an embedded server but
you can use other embedded servers like Jetty (Eclipse),
Undertow (Jboss)

Verify whether you can use undertow in your application

Spring Rest webservices


Webservice:
Dependencies required to create webservices
1. Web
2. Devtools

How to design ReST based webservices


1. Applications must use HTTP methods to specify the type of
operations like GET, POST, PUT, DELETE
2. Applications must provide URL end points to their clients so
that they can use it to access the resource
Ex: /balance is one endpoint a service can use to fetch the
balance, so that client programs (phone-pay, google pay,
atm machines) would use /balance to get the balance from
the service
3. In Spring you have an annotation @RestController to mark a
class as a Rest Webservice
4. In Spring you need to use @RequestMapping to specify the
URL, then for http methods you can use annotations like
@GetMapping, @PutMapping, @PostMapping,
@DeleteMapping
@RestController
@RequestMapping(“/myapi”)
class MyResource {

@GetMapping(path = “/balance”)
public String fetchBalance() { … }

@PutMapping(path = “/update”)
public String updateBalance() { .. }
}
Get /myapi/balance calls fetchBalance
Put /myapi/update calls updateBalance
Postman client: It is an application used to test the webservices.
Writing a simple webservice & test from the postman
@RestController
@RequestMapping(“/myapi”)
public class MyResource {
@GetMapping
public ResponseEntity greet() {

return ResponseEntity.status(200).body(“Some text


message”)
// we can also return JSON data using Map api
Map map = new HashMap();
map.put(“message”, “some message”);
return ResponseEntity.status(200).body(map);
}
}

How to read JSON data of the Request and map to the Java object
in Webservice
@PostMapping(path = “/store”, consumes =
MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> method (@RequestBody
Employee emp) {
// Spring Boot maps each json property to the Employee object
properties automatically
// you can use that object to pass to the Service layer
}
How to read data coming from the URL parameter
We must parameterize the path in HTTP methods
@GetMapping(“{id}”) and extract that value using
@PathVariable(“id”), if you send /200, then the
@GetMapping(“{id}”) will have value 100 in it &
@PathVariable(“id”) will extract that value 100.
@PutMapping(“{id}/{phone}”), now it matches to the url
/100/9292393, and we must have @PathVariable(“id”) &
@PathVariable(“phone”) to extract these values

Things to create
1. Employee class with id, name & salary and setters, getters
2. Webservice that can accept JSON & map to the Employee
object
3. Webservice that can accept path parameters.

There are 2 more mappings you can do in REST which are


@PutMapping
@DeleteMapping
These are used based on the type of operation you want to do,
Put: It is to update any existing resource
Delete: It is to delete any existing resource
Day 3 Agenda
 MySQL Database
 Spring Data JPA
 CrudRepository
 Layered architecture like Controller, Service, DAO
Spring Data JPA
It is a starter library provided by spring boot to interact with the
database, it takes care of auto-configuring many things required
for database
1. Establishing connection
2. Generating the SQL queries for the database
3. Implementing the database operations using some
repository interfaces, it doesn’t need DAO layer
implementation

Layered architecture
Controller layer: Takes care of processing the request &
generating the response, it accesses service layer
Service layer: Takes care of implementing business logic, it
accesses DAO layer
DAO layer: Takes care of implementing database operations i.e.,
CRUD operations
Dependency of objects
Controller depends on Service, and service depends on DAO layer,
in spring boot we can make use of Dependency injection feature
and let spring to supply the respective dependencies
Benefits of Spring Data JPA
1. You get interfaces that provides all the CRUD operations
a. CrudRepository<T, ID>
b. JpaRepository<T, ID>
2. You don’t have to implement the DAO layer, spring boot
takes care of implementing the DAO layer based on the
interface you create
3. You don’t have to write code to establish connection, instead
configure database properties in application.properties,
spring boot takes care of establishing connection
4. Uses ORM framework so that your entity class can be
mapped to the table
CrudRepository provides methods like save(), delete(), findAll()
methods
JpaRepository extends CrudRepository and provides some extra
methods for sorting & pagination
Steps
1. Add below libraries in your project
a. Spring Data JPA
b. MySQL Driver
2. Create entity class that maps to the employee table, mark
primary key property
3. Structure the project to have separate packages for separate
layers like controller, service, dao and etc.
4. Create a repository interface that extends either
CrudRepository or JpaRepository (this gives spring boot an
idea how to implement the repository)
Note: Spring Boot provides an auto-implementation &
registers that object in the spring container
5. Create a service layer that uses repository interface to
perform operations
a. We must create an interface in Service layer that is
used by the clients (Controller)
b. We must implement that interface to provide
implementation for all the methods of the interface
6. Controller must call the service layer methods
7. Configure application.properties to have datasource
information’s

You might also like