Spring Boot and MicroServices
Spring Boot and MicroServices
19-02-2021
Pre-Requisites:-
Core Java
Adv Java(jdbc, servlet & jsp)
SQL (Curd Operations)
ORM Basics
Course content:-
We are dividing into 5 parts
1. Spring Boot Internal
2. Spring Data JPA
3. Spring Web MVC Architecture
4. Restful Services
5. MicroServices
Part 1:- Spring Boot Internals
1. What is Spring Framework
2. Spring Vs Spring Boot
3. Advantages of Spring Boot
4. SpringBoot Application Creation—Spring Initializer,Toolsuit
5. Spring Boot Starter POM
6. Start/main class in Spring Boot
7. @SpringBootApplication annotation
8. @AutoConfiguration in Spring Boot
9. SpringApplicaiton.run method
10. Spring Boot BootStraping Process
11. IOC container
12. Dependency Injection---CI,SI,FI
13. Autowiring and Qualifier
14. Component Scanning
15. Stereotype Annotation
16. Bean life cycle
17. Banner in Spring
18. Runners in Spring Boot---
ApplicationRunner,CommandLineRunner
Component Scan will start from Base Package after that it starts the
subpackages. The Packages start with the basepackage name is called
subpackages.
Com.sattibabu--- base package
Com.sattibabu.Beans—will be scanned
Com.sattibabu.Controller ---will be scanned
In.sattibabu --- will not be scanned.
@Component:- used for general purpose and used for Spring Bean
@Configuration:- used to represent as a Configuration class.
@Bean:- if we want to customize the Bean creation we will go for
@Bean creation. Bean is a method level annotation rest are Class
level annotation.
09-03-2021
Constuctor Injection:- By Using Parameterized Constructor.
Dependent Object is injected to the Target Object through the
Constructor.
@Autowired
Public class Car{ //Target Class
Private Engine eng;
@Autowired
Public Car(Engine eng){ //Target Constructor.
this.eng=eng;
}
}
Setter Injection:- Dependent Object is injected By Calling Setter
method of the Target. Injecting through Setter Method
@Autowired
Public class Car{
@Component(“de”)
Class DieselEngine implements IEngine{
}
@Component(“pe”)
Class PetrolEngine implements IEngine{
@Autowired
@Qualifier(“de”)
IEngine eng;
Autowiring:- Autowiring is the process of identifying the dependent object
and inject into that target object. It is applicable for only object not into
primitive and not for Wrapper classes.
11-03-2021
Banner in Spring Boot:-
When we run the Spring boot applications spring logo is printing on the
console that is called as Banner. Banner printing is a part of
SpringApplication.run(..)method.
Sprint Boot banner is have 3 below modes:-
1. OFF
2. LOG
3. CONSOLE(DEFAULT).
If we set the LOG banner will be printed in log file as well. We can
customize banner text in Spring Boot by creating banner.txt file in
src/main/resources folder. ASCII characters need to given.
spring.main.banner-mode=off
if we want to off the Banner. In src/main/resources folder.
13-Mar-2021
15-Mar-2021
Persistence Layer:- This is used to Communicate with Database.
Best Practice for Persistence Layer:-
1. For every table we should create one DAO Class. If we don’t follow
this there is a problem of Single Responsibility Principle.
Role_master Role_Master_DAO.java
User_Table User_Table_DAO.java
2. For Every Database Table we should have 4 columns
a. createDate
b. CreatedBy
c. UpdateDate
d. UpdtaedBy
3. For Every Table maintain a Primary Key
a. Primary key---Not Null & Unique
4. If we perform Search operations we should use the indexes in the
table.
5. Create Connection pool to avoid connection Exhausted Problem.
6. Implement soft Delete for tables.--- Delete from Application level
Inactive from the Table.
7. Use Generators to Generate the value for Primary Keys.
8. Write Database Independent Queries.
16-Mar-2021
By using Hibernate also we have to do some boiler plate code.
Insert record using Hibernate
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
------------------------
Configuration cfg=new Configuration();
Cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session hsession=sf.openSession();
Transaction tx=hSession.beginTransaction();
Hsession.save(query);
Tx.close();
Inserting record using Spring JDBC
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-----------------------------
JdbcTemplate jdbcTemplate;
jdbcTemplate.update(sql);
Insert record using spring ORM
HibernateTemplate hibTemplate;
hibTemplate.save(entityObj);
by using JDBC we are dealing with Text Data. When we go for hibernate
we don’t go for text data we will use as objects. We have four options
already why do we go for
Spring Data JPA:- For executing CRUD operations we have to perform
1000 times if we have 1000 tables. It’s again boiler plate code. Data JPA
main purpose is used to reduce the boiler plate code while performing
CRUD operations.
spring.jpa.properties.show_sql=true
22-Mar-2021:- No class
23-Mar-2021
When we write HQL queries database will not understand it should be
converted by Dialect classes. We can configure the dialect classes in our
property files.
@query(“ “) ---- HQL query
@query(value=” “, nativeSqlQuery=true);
SQL--- select * from EMP_DTLS will use Table names
HQL Query:- from Employee where empName=”ram”; ---It uses entity class
name and entity properties.
24-Mar-2021
Spring Data JPA Overview.
CrudRepository is extending from Repository which is a marker interface.
CrudRepository consists of 11 methods.
26-Mar-2021
Generators:- Generators are used to configure the values to the primary
key. It will use internally Hibernate_sequence for generating Primary key
value.
How to create custom generator in Spring Boot?
@GeneratedValue(generator=”user_Seq”,
strategy=”GenerationType.SEQUENCE”);
If we want to define our own generators
Custom Generators:-
Generators are used to generate the value for Primary key column. There
are certain generators are available based on user requirement we will
create custom generators.
Use case:- TCS emp id
TCS01,TCS02,
OD1,OD2,OD3.
To create custom generators we should implement the IdentifierGenerator
interface. We have generator() method in the interface. We have to write
the logic in that method. The primary key will be devided into two parts.
PrefixOD
Suffix-Number(starts with 1 increment by 1);
Step to Develop a Spring Data JPA with custom Generators.
1. Creating Spring starter project with below dependencies
a. Spring-boot-starter-data-jpa
b. Oracle driver
c. Lombok project
2. Create an entity class using annotations.
3. Create sequence in DB for suffix value generation.
4. Create custom generator class by implementing Identifier Generator
Interface.
5. Configure custom generator in Entity.
6. Create Repository Interface by extending Repository Interface.
Transaction Management:-Unit amount of work is called a Transaction.
30-03-2021
Connection Pooling:-
To perform CRUD operations we need database connection. JDBC
connects with DB by using
Connection con=DriverManager.getConnection(“”);
This is called physical connection.
If we use connection pooling. Data JPA will help to get connection this is
called logical connection.
Spring Boot will use Hikari to connect with Database. If we don’t close
Hikari will close the connections.
We can customize the Hikari Connection pool properties in
Application.properties or Appliction.yml file.
Ideal time for Connection
Min size no of connections
Max size no of connections.
Spring.datasource.hikari.idleTimeout=1000
Spring.datasource.hikari.connectionTimeout=3000
Spring.datasource.hikari.maxLifetime=180000
In SpringBoot 1.x version we have to add the hikari dependency in pom.xml
In springBoot.2.x version its inbuilt property.
31-Mar-2021
Spring MVC:- Spring MVC is one of the module in the Spring frame work.
It supports two types of applications.
1. Web Applications
2. Distributed Application
Advantages of Spring MVC:-
1. It supports loosely coupling
2. It supports form binding. It provides flexibility in form binding
means it will take care of the type casting.
3. It can support multiple presentation technologies.
4. Components roles are clearly defined.
Every request should be handled by individual controller. For avoiding this
we are using Spring MVC architecture. It uses front controller. It will take
care of common logics required for all the controllers.
01-Apr-2021
Spring MVC module is developed based on 2 design patterns
6. View
05-Apr-2021
1. Create Spring Boot Application with below dependencies
1)spring-boot-starter-web
2)tomcat-embed-jasper
3)spring-boot-devtools
2) Create Controller Class using @Controller annotation
model.addAttribute("name", "Ashok");
model.addAttribute("user", userObject);
model.addAttribute("books", booksList);
Syntax : ${key}
We can send direct raw response also from controller using @ResponseBody annotation
@GetMapping
public String getUserData(Model model) {
model.addAttribute("user", userObj);
return "user-data";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Books Available</h3>
<table border="1">
<thead>
<tr>
<th>Book Id</th>
<th>Book Name</th>
<th>Book Price</th>
</tr>
</thead>
<tbody>
<c:forEach items="${books}" var="book">
<tr>
<td>${book.bookId}</td>
<td>${book.bookName}</td>
<td>${book.bookPrice}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
07-Apr-2021
We can send data from UI to controller in below ways
1) Request Param
2) Path Param
3) Forms
If we want to send small piece of information then we will use Request Param or Path Param
Request Param and Path Param will represent data in URL directley
Using Forms we can send data in Request Body.
08-Mar-2021
When we submit form then form data will go to server in key-value format.
-> Spring MVC having form binding support. It will capture form data and
will store into object.
-> Form fields keys should match with our class variables then form data
will be store into objet.
-> If we submit form with GET request then form data will be appendend to
URL (It is not secured).
-------------------------------------------------------------------------
-> To simplify forms development Spring MVC provided Form Tag library
-> Spring MVC form tag library contains set of tags like below
<form:form>
<form:input>
<form:password>
<form:radioButton> & <form:radioButtons>
<form:select> & <form:option> & <form:options>
<form:checkbox> & <form:checkboxes>
<form:hidden/> etc...
-> Inorder to use spring mvc form tags in jsp, we should add taglib directive
with spring mvc form tags url.
10-Apr-2021
As part of Form tag library several tags are available
form
input
password
radioButton
radioButtons
checkbox
checkboxes
select
option & options
package in.ashokit.domain;
import lombok.Data;
@Data
public class Student {
}
-------------------------------------------------------------------------
package in.ashokit.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import in.ashokit.domain.Student;
@Controller
public class StudentController {
@GetMapping("/student")
public String loadForm(Model model) {
// Form Binding Object
Student s = new Student();
model.addAttribute("student", s);
@PostMapping("/student")
public String saveStudent(Student student, Model model) {
System.out.println(student);
return "student";
}
}
------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<font color='green'>${succMsg}</font>
<tr>
<td>Course</td>
<td><form:select path="course">
<form:option value="">-Select-</form:option>
<form:option value="java">Java</form:option>
<form:option value="testing">Testing</form:option>
<form:option value="python">Python</form:option>
</form:select></td>
</tr>
<tr>
<td>Timings</td>
<td>
<form:checkbox path="timings" value="mrng"/>Morning
<form:checkbox path="timings" value="noon"/>Afternoon
<form:checkbox path="timings" value="evng"/>Evening
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Register"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
11-Apr-2021
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
package in.ashokit.domain;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Value;
import lombok.Data;
@Data
public class Student {
@NotEmpty(message = "{validation.firstName.notEmpty}")
@Size(min = 3, max = 8, message = "Minimum 3 and Maximum 8 characters are
allowed")
private String firstName;
@NotEmpty(message = "{validation.lastName.notEmpty}")
private String lastName;
@NotEmpty(message = "{validation.email.notEmpty}")
@Email(message = "Please enter a valid e-mail address")
private String email;
---------------------------------------------------------------------------------------------
package in.ashokit.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import in.ashokit.domain.Student;
import in.ashokit.service.StudentService;
@Controller
public class StudentController {
@Autowired
private StudentService service;
@GetMapping("/student")
public String loadForm(Model model) {
@PostMapping("/student")
public String saveStudent(@Valid Student s, BindingResult result, Model model) {
System.out.println(s);
if(result.hasErrors()) {
return "student";
}
//store form data in db
model.addAttribute("succMsg", "Registration Successfull");
return "student";
}
@ModelAttribute
private void loadFormData(Model model) {
System.out.println("******* loadFormData() method called ******");
model.addAttribute("genders", service.getGenders());
model.addAttribute("courses", service.getCourses());
model.addAttribute("timings", service.getTimings());
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<font color='green'>${succMsg}</font>
<tr>
<td>Course</td>
<td><form:select path="course">
<form:option value="">-Select-</form:option>
<form:options items="${courses}" />
</form:select></td>
</tr>
<tr>
<td>Timings</td>
<td><form:checkboxes items="${timings}" path="timings" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</body>
</html>
package in.ashokit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@SpringBootApplication
public class Application {
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
}
-------------------------messages.properties---------------------------------------------