KEMBAR78
Spring 8PM Running Notes | PDF | Spring Framework | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
57 views61 pages

Spring 8PM Running Notes

The document outlines a training program for Spring Framework, focusing on practical application and real-time project implementation. It emphasizes the importance of Spring in Java development, covering topics such as Dependency Injection, Inversion of Control, and various Spring modules. The training includes internal sessions, materials, and assignments, with classes scheduled for two months, aimed at enhancing practical skills over theoretical knowledge.

Uploaded by

hekite7444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views61 pages

Spring 8PM Running Notes

The document outlines a training program for Spring Framework, focusing on practical application and real-time project implementation. It emphasizes the importance of Spring in Java development, covering topics such as Dependency Injection, Inversion of Control, and various Spring modules. The training includes internal sessions, materials, and assignments, with classes scheduled for two months, aimed at enhancing practical skills over theoretical knowledge.

Uploaded by

hekite7444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 61

Dilip Singh

I am From Hyderbad
10+ Years Ex in JAva Devlopemnt
Currently Aloso I am working for USA Company
Helath Care Domains

Spring Boot and MicroServices

Spring Framework.

Spring Framework :

Pre-Req:
Core Java

Adv. Java :
Basic knowledge JDBC
Basic knowledge Servlets

Request/Suggestion: Please go through Knowledge

Spring FW: Very Easy

how the Training :

1. Internal Training to Java resources/employes


2. Lot of Interviews : freshers to 0 yers exp

HCL
Infoys
Accenture
COgnizant
BankOFAmerica

lot of knowledge, We have to be very practical


Programming

More practical then theory

less theory , more practical.

open google, theory :

int a, int b;
a+b;

int principalAmount;
int intrestAmout;

toatl =

Theory :
Every : thoery :
Make your hands Dirty:

Inheritenc :

User extends Customer{

A extends B : Thoery
R15 extends Bike : thoery

3. Material/Notes

Create Google Class room.


Runnng Notes,
Materila I will Upload

Assignments in class room

upload daliy example class room

4. Content of Course

Spring Framework :

Content is defined by considering Real time usage of Spring FW.

Real time Projects Implementation :


Concepts more being used
indireclty Those things will be asked Interview

Basic level Expert. Panel :


Interview : Panle
Core Module
MVC Module
Spring Devloper
10 Modules

Spring
Core
JDBC
JPA/ORM
MVC
Security

5. Timings and Duration

Class Duration : 1.30 Mins


8 PM IST - 9.30 PM
Mon-Saturday

2 Months of time

6. Question and Answers


Class Room
7. Attendence :

Training :
You will always have internal link to up coming concepts.
internally dependecy

8. Importance of Spring Fw w.r.to our carrier

core Java
Adv . java
Spring FW

in evry relatime project, 100% we will use


Frameworks built on top of Core and Adv. java

1. Must & should for Java Developer


2. Spring Boot and Micro Serices

Spring FW

Core java lang


Adv java
Programming Langs

Progrming Lang vs Framework.


Progrmaing lang:

Key Words
Set of rules

Set rules

public class classnmae{

Programing Langugae:
Set of rules but not solution of any existing problems
or better approaches fo writing code to complete the our requirement.

Framework : Logics
Solutions on top of Progrming lang.

Solution of existing problems


Better solution comparing with Progrmaing

Every real Time project always implemtns by using frameworks.


Spring FW
Spring BOOT
Spring Hibernate
Qurkaus
Struts

Devleopment is very fast

To execute SQL of slect : 10 line of code : JDBC : 5 mins


Spring FW: 1 line of code : 1 min

Servlets:
To create web application,
Web functionalites :
Hello world

10 line of code in Servlets :

HelloWorldServelt extends HTTPSrvlets{

service(){

//reposne : Helo world

HWelomServelt extends HTTPSrvlets{

service(){

//reposne : Welome

web.xml

<servlet config>

15 min :

3 lines : 2 to mins

Please end wel come message to Browser

15 mins

10 lines of code : 5 mins : Spring

Spring Framework:
=================

introduced in 2003 : Rod Jhonson :


Spring FW is relased as group of Modules.

Core Module :
Core Functionalitie os Spring FW
How Spring FW working
Benefits OF Spring FW
Principle or Designs folowed as part of SPring FW

Very Important :

Data Module: JDBC :


Database :
How to interact with Data base with SPring FW
PErform Data base operations :
Executing DB queries
Spring Provided : Predfined functionalities

Web Module : Servlets :

Creating web applications


WEb Functionalites
create REST API services
Security Moudule :

What is security in Application


Enabling Security
Providing Security to the Application

Core Module :
Spring Release Versions
Advantages oF Spring FW
Spring FW principle

// not allowing suplicate

String[] names : 100 Size

name[0] = Dilip
name[10] = Dilip
name[20] = Dilip
name[99] = Dilip

when ever you are trying to add value to array


iterate your
Dilip
for(){
is Dilip vaibale ?

1 hr : 50 line s

Hashset <String> names = new Hashset();


names.add(Dilip)
names.add(Dilip)

names : Dilip

Advantages of The Spring FW:


============================

1. Dependecy Injection :

2. IOC (Inversion Of Controle)

1. Dependecy Injection :

Instead of writing logic of creating objects in program/code level

Spring is expecting us from like, please provide details of classes to


Spring FW, so that spring will create objects of our classes and
Spring will passs newly created wherever we want in progrme.

Eliminating Logic of Creation of Objects

1. Define/Impllment classes :
2..Don't create Objects : new keyword logic
3. Configure/pass info to SPring FW
4. Spring will create Objects
5. Request Objects from Spring FW
6.

Dependents of Our parents


Parents are accommodating all our needs :

JAVA Object O PL. Spring FW : java lang


class and the we will create Objects
create Objects : jvm

1. who created Objects Address and Employee classes?

JVM

2. Who injected dependecy of Object Address into Employee Object?

JVM

3. As per Logic, As a developer to create Objects of Address and Emplyee classes

what I did?

using new key word.


IOC (Inversion Of Control) :

----------------------------
Inversion : Reversal

Controle : Taking of Controle

Inversion Of Control is known as implemenation DI.


IOC is a principle in sofatware engineering:

Transfering the control of object creations , data configurations and maintinging


life cycle of Objects.

SPring IOC Container : Spring FW : Spring Core Module

- Creating objects
- Configuring oBjects
- Maintaining Lifecycle of Objects

IOC COntiner : Internally implementing DI concpet in between Configured Objects.

SPring Project :

Spring Core Module :

Spring FW is realsed as multple jar files. Al modules

Identify jar of Core Module:

Spring Versions History:

2003 in MArket

Spring V1 : 2004

2023
Current released or running Spring version is 6...

In Training , we are going to use Spring 5

1. Downlaod Spring jars

2. Create A java Project : Eclipse


New -> Java Project
Finsih with name
3. Identify Spring Core jar file to make our project as Spring Core Module
Project

5 jar files

4. Attach these jar files to our java project : demo


BuildPath

5. Right click on project :


Build path -> Configure Build path -> class path
6. Add external jar
select 5 jars

Our project is ready to Suppoert Spring Core Module.

Dileep
Day-1 https://youtu.be/uDp60mj2KGU
Day-2 https://youtu.be/o5Iu8Hm16iE
Day-3 https://youtu.be/cinbLbNTLxA
Day-4 https://youtu.be/-mRrBinhwRg

Spring @ 8.00 PM by Mr. Dileep from 26th June 2023


Fee-3500/- (including GST) without videos

Note : full stack java student also can attend the class if the clear all the fee
for full stack java
Spring @ 8.00 PM by Mr. Dileep from 26th June 2023
Fee-3500/- (including GST) without videos

Note : full stack java student also can attend the class if the clear all the fee
for full stack java

Note : If any new student is interested in this batch means pay the 3500-/

Note : After the payment please fill the form if you want regular class link means
👇
http://bit.ly/Spring8DLP

Akhil (Admin)
Mobile: 91541 56192 (Only Whatsapp)
please read clearly what did i mention

1. project Setup

1. Define/Impllment java classes :

Address

3. Configure/pass info to clases with SPring FW: Spring IOC Container

1. XML Configuration
2. JAVa/Annoatation Confgiuration

1. XML Configuration: in side XML


Spring FW providing an XML schema to configure our Java classes.

Spring provided many pre defined xml tags to configure our classes
information

4. Spring will create Objects


5. Request Objects from Spring FW
6.

Spring Bean : Bean/ Bean class

It's n/b a java class that to configuring with Spring GW.

public class Address {

private String city;


private String state;
private int pincode;

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getState() {


return state;
}

public void setState(String state) {


this.state = state;
}

public int getPincode() {


return pincode;
}

public void setPincode(int pincode) {


this.pincode = pincode;
}

Addees calls informatio with Spring FW,


Now I am calling Address classas Sprig Bean Class.

create xml file


beans.xml

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


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<!-- bean definitions here -->

</beans>

XML file is ready

Address.java
Address class information provising to Spring FW
Choice of Object creation to Spring FW
Spring Bean Class

Student.java

public class Student{

Don't wan to provide to Spring FW, then we should not call it as a Sprign bean.

Clasess are configured with Spring FW are called as Spring Bean classes.

Which are not configured are should not be caled as Spring beans.

Addess addr = new Addess();

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


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<!-- bean definitions here -->

<bean id="addr" class="com.naresh.it.Address" >

</bean>

</beans>
Spring IOC container is nothing but Object of Sprig PreDefined Class.

IOC Container callses :

BeanFactory are from Spring FW

beans.xml :

1. Define/Impllment java classes :

Address

2. Configure/pass info to SPring FW/ Spring IOC Container

1. XML Configuratuon
2. JAVa/Annoatation Confgiuration

1. XML Configuratuon:

3. Create Spring Continer Object


Spring will create Objects
4. Request Objects from Spring FW
5.

Address adr1 = new Address();


//Object Name / Reference

Address adr2 = new Address();


Address adr3 = new Address();
adr2.setProductName("iphone ");
adr3.setProductName("smasung");

javac Test.java
java Test

Why <beans>
<bean> we provided our class information.

1. Create JAva Classes : Address


2. create xml file : beans.xml
3. in side XML file, we are configured/provided information of Address

<bean id="Objectname" class="FullyQualifiedClassName i.e.pack+class">

<bean>

4. Now we create Spring IOC conatiner Object with help of BeanFactory


interface
Implemented classes from SPring FW:
XML config Opetion :
FileSystemXmlApplicationContext("path of our xml file");

5. getBean(....Bean ID )

Can I configure Same class multiple Times inside Spring Configuration?

Address add1 = new Address();

If I given wrong Bean Id as part of getBean();

what is a Spring Bean class?

classes what we are configured with Spring FW are called ass Spring Bean
classes.

Address : Spring Bean

Product : is it a Spring Bean class?

Java Class As a Spring Bean class?

Java class : Employee : Obj not going to be created BY SFW.

productName = Iphone
price = 100000
productID = 14

// Create Object
ProductDetails product = new ProductDetails();

//2 nd step : By using Setter methods : Setting value to Instace vaiables

why can't we set directly with variable


obj.variable = 14

//Injecting Values of properties into Object


product.setProductName("IPHOne");

Dependecy Injection :

Creating OBjects
Spring Injecting those Objects to another Objects called DI,

Spring, Who is creating Object for ProductDtails

So that Iam request SFW , could you please inject data of instace varible of
class Product Details.
After creation Object , I want to Inject data for instance variable/properties
of Object

productName = Iphone
price = 100000
productID = 14

When Object create all instace variable are initilized with default values.

private String productName; // null


private int price;
private String productID;

To inject values/Objects to another Objects Spring Provided 3 Types Dependecy


Injection.

XML file Config :


1. Setter Injection
2. Constructor Injection

3. Filed Injection // Not XML config

Java / Annotation Configuration

1. Setter Injection
2. Constructor Injection
3. Filed Injection

Setter Injection :
=================

To achive Setter Injection :

Spring Provided a child xml tag for <bean> called as <property>

<property> we are achieving setter injection.

1. IOC creating Object for our Bean class with default values of Instance
varibales/properties.
2. Once Object created , After Object Creation , Spring Injecting confgigured value
of properties into Object.

<bean id="product1" class="com.products.ProductDetails">

<!-- name is instance varibale name -->


<property name="productName" value="Iphone"> </property>
<property name="price" value="199999"> </property>
<property name="productID" value="iphone14"> </property>

</bean>

Spring calling setter methods with object crated in step 1


<property name="productName" value="Iphone"> </property>

product1.setProductName("Iphone");
product1.setPrice(199999);
product1.setProductID("iphone14-2022");
Spring injected value of propertie via setter methods of our bean class.

1. can I DO multiple bean confgiurations for same Java class?

Spring FW trying to separate real time data including as part of programming/coding


level.
Spring provding loosley coupled.

// Tightly Coupling : programming Logic with values


// Probles may come
//
// java file : Re-comiplationn
Address adr2 = new Address();
Address adr3 = new Address();
adr2.setProductName("iphone ");
adr3.setProductName("oppo");
adr3.setPrice(32323);

Modify data inside java logic


adr3.setPrice(25000); //

w.r.to : SFW :

//Setter Injection with r.to diffet tyeps

1. Injecting primitives
2. Injecting String data type
3. Collection Objects
List
Set
Map
4. User Defined/Predefined classes Objects / Other class Objects

private long orderId;


private double orderPrice;
private boolean isOrderDeliverd;
private Set<String> items; // Group of values

coke,
choclate,
water bottele
List : <list> child tag of <property> tag
Set : <set> child tag of <property> tag

as part of <list> : child tag <value>


as part of <set> : child tag <value>
as part of <map>
<entry key="" value=""></entry>

</map>
Please try to inject : Set of values

set+VariableName

mobileNumber

setMobileNumber
getMobileNumber

<property name="itemsPrices">
<map>
<entry key="Coke" value="60"></entry>
<entry key="choclate" value="100"></entry>
<entry>
<key>Water Bottle</key>
<value>20</value>
</entry>
</map>
</property>

primitive
String
Collection Objects

USerDefined Classes /PreDefined class

Collectiing Details of Students

studentId
studentName
mobileNumber
Address
Address
String city
String state
String country
int pincode

Student depends on Address Object

ref : attribute : refernce


representing another bean ID n/b another Bean Object

Constructor Injection:
=======================

Constructor : Java, It ia block of code which will be executed while Object


creation.
to initlize deafault values to instance variables
.

public class Student{

String clgName;
string sname;

Student(){
clgName = "ABC clg";
sname = "Dilip";
}

Student(String clgName){
this.clgName = clgName;

Student(String clgName, String sanme){


this.clgName = clgName;
this.sname = sname;

// Student s= new Student();


Student s= new Student("XYZ clg");

Student s= new Student("XYZ clg", "Dilip");


}

Constructor Injection (CI):

BAsed on beans confgiuration: If we are using


<bean>
<constructor-arg name=" " value=" ">
//Passing value to Constructor parameters
//

Spring FW, I need CI.

Dependecy Injection happens while Object Creation with Constructor execution.

1. If No default Constructor implemented


and

If we implemneted Params Constructor

// Only SI
//ONLY CI
// BOTH

2. If default Constructor implemented


and

If we implemneted Params Constructor


// Only SI
//ONLY CI
// BOTH

Setter vs

1.Objet create
2. After Obj creation, Calls Setter methods
3.<property>

Constructor Inj:
1. Spring Injecting value while Object creation
Constructor : BY pasing Our all value to Constructor args.
2.<constructor-arg>

Asg :
Set of Value
Map Object

pid;
pname;
price;

productId;
productName;

CI:
primitives
String
Collection LIST,Set, Map
Injecting Another class Objects

index : value should be injected to which poition of constructor argument

index starts from 0 : if index provided,No need to maintina order

Setter Vs Constructor Injection:


================================

We can't say setter is beetr or constructor better injection.

Order :
3 properties :
30 properties

String orderId;
double orderValue;
// Class
Product product;

//30 Proprties // 10 mandatoy 20 may optional

Order(){
}

Core Java:

Order o = new Order();


o.setOrderId(1)

DatabaseConnection (userName,url,psasword){

}
url
userName
pwd

Bean Wiring :
============
Bean Wiring :

AutoWiring in SP :
=====================
autowire =""

Class A{

B b;
C c;
D d;
E f;
// 7 anotherr classes

B
C
D
E
F

//Small instrution to SPF, based on Bean Classs/Name/ID if


<bean id =a class=A>
//If A needs Be object, automaticcy Inject / wire that B object in Side

</bean>

IOC Containers:
========
1. BeanFactory : org.springframework.beans.factory
2. ApplicationContext : org.springframework.context
Bean Wiring :

Autowiring :
Feture enables
injecting dependent Objects internally/implicitly by SFW.
Internally Spring Identifying Dependent Objects and injected ot the Other Baan
Objectss.

Autowiring will be used for only reference Objects.

Autowiring will not support primitives and String Data injects.

A need B
Bean B b:
<bena id ="a" class=''''>

</bean>

A{
B b;

1. 4 ways

1. By Default is Spring Not supporting.


2. To eanbale autowiring in spring w.r.to. XML config.
we need to use an attribute called as autowire as part of <bean>.

3. autowire attribute will support 4 values.


1. no : No Autowiring. This is defult value.

2. byName : Property Name

Inforaming to SPF, please inject Dependecy Object which matches with bean id
and property name of class.

bean Id of Product = property name of Order

prod != product

3. byType : Spring Injects Objects of same Data type Object.

Spring will not consider property name of class.


public class Order {

private String orderId;


private double orderValue;
private Product product; // null

<bean id="product" class="com.flipkart.product.Product">


<constructor-arg value="101"></constructor-arg>
<constructor-arg value="Hp Laptop"></constructor-arg>
</bean>
<bean id="product2" class=com.flipkart.product.Product">

</bean>

byName and byType are working only with setter Injection.


SI, definelty we beed a default /0-params Constructor

4. constructor : Constructor Injection :

autowiring : XML

Annoataion :

Dilip

Spring FW: we will use 70% Annoataions


20% XML

Bean Scopes:
============

Spring Creating Objects of Beans classes.

Visibility of Bean Object in Spring application memory level at runtime.

Whenever Spring created a bean Object of one bean Configuration

<bean id="productOne" class="com.flipkart.product.Product" >


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>

Spring Creating Singleton Object by default.

Singleton Object:

Only One Object per application.

2nd Object :
It will check IS there any Object avilable with same class
if Object avliable
return Same Object
if not avlible then create object
return newly created Object.

5 types :
Bean Scopes : We can change default Object creation behaviour which is doing by
SFW.

Define bean scopes with an attribute called as "scope" as part of bean


configuration.

1 singleton : Default bean scope


IF we are not provided any scope atrribute value along with bean
configuration, internally by default Spring adding scope=singleton

Whenever we are calling/requesting bean object with bean ID from Spring IOC
container, Sprig will return same object again and again.

Spring IOC continer maintains only one object for that specifc bean ID.

2 prototype
For every IOC call getBean(), Spring creating a fresh/new Object and
returing.

3. request:

For Every new incoming HTTP request. SPring IOC conatiner will creates new
instance/ Bean Object.

4. session
scope=session for a bean, Spring will returns new Bean Object for every new
Session Object.

5. application
scope=application, Spring IOC conatiner creates only one bean Object and it
will be attached to ServeletContext in side Spring WEb/MVC module

6. websokcet : WebSocket

Java Based/Annotations based Configuration:

1. How to create bean Objects / how we are passing informatio to SFW.


2. Setter Injection / Constructor Injection
3. Aurowiring
4. Bean Scopes

@Bean(scope="singleton")

Java/Annotation Based Configuration:


===================================

many annotations provided by SPring FW.

XML
<bean id="student" class="com.tek.teacher.Student">

</bean>

<bean id="student2" class="com.tek.teacher.Student">

</bean>
@Configuration
public class BeansConfiguration {

//Student Bean class Configuring

// Bean Object creation method


@Bean
public Student getStudent() {
return new Student();
}

1. Define Bean Class : Student.java


2. Spring provided an annotation called @Configuration

@Configuration :

By using @Configuration annotation we are configuring bean classes.

@Configuration will be used at class Level.

We are going to write a java class and that will called Configuration classes

How we are going to configure Bean classes in Configuration claases?

Spring provded another annotation called as @Bean

Inside Configuration classses we are going to write bean creation methods and
those methods will be delared wiht
@Bean annoation.

1. Bena class
2. configuration
3. IOC Container

Caused by: java.lang.ClassNotFoundException: org.springframework.aop.TargetSource

To reslove this : add spring-aop.jar file in Build Path

Spring will not create Object of Bean classes automatically even if we are
configured as part of Configuration classes.

While Creating/After creating ICO conatiner/Application context ,

we should provide Configuration classes Information ot IOC container.

AnnotationConfigApplicationContext context =
new
AnnotationConfigApplicationContext(BeansConfiguration.class);

Student student = (Student) context.getBean("student");


System.out.println(student);

Student student2 = (Student) context.getBean("student");


System.out.println(student2);

Assignment:
We can create many beans xml files
2 bena
2 benas

Configuration class : Beans.xml

@Bean = <bean>
In side, we are configuring Bean Object

AnnotationConfigApplicationContext // Creating oBject of IOC continer

passing COnfifuration classes to IOC COntiner

//getBean();

Please calcuate avergae and total of Students marks

sub1 = 88
s2 =99
s3 =100

(s1+s2+s3)/3

Basic Java Based Configuration


-> Configuration classses
-> Bean methods
-> How to handle multiple Bean Config classe
-> How to pass Configuration classses to Application Context

Class : Pojo Class : Student


@Configuration
in side
@Bean method

@Component:
1 to 5 classes :

// Manual Confguration

100 classes
@Confgiuration
{

@Bean
...Class1...........

@Bean
.....Class2.........

@Bean
............Class3.....

@Bean
@Bean

@Bean
@Bean

@Bean

@Component: this annoation allows Spring to detect our bean classes


automatically. and Spring will create Bean Objects.

@Component will be used at class level.

base Package : Componet classes Derived packages

Req :

Only One Bean Object enough


@Component : One Object

DBConnection{

More than one Bean Object for same class


@Config
@Bean
getDbConnection

DBConnection{
url,username,pwd
}
Only one Object : with some values confgured
@Component

Order

@ComponetScan : will be used along with @Configuration class and class level

contect.scan();

1. @Component

2. 10 Configuration classes

50 classes

Default Object s

50 classes
confgiured with value s

Scope of Beans :
================

Default Scope :

1. No Component name, then class name as Bean Id


2. No Bean Name in Confgi. class, then Bena Id is method name;.

@Scope: To define scope value of a bean

this annoation is used at class level if it is component


at @Bean method level

@Autowired :

this annotation will be used for automatic dependecy Injection.

addedd @Autowired Dependy object level

WARNING: Exception encountered during context initialization - cancelling refresh


attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'employee': Unsatisfied dependency expressed through field
'address'; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying
bean of type 'com.naresh.it.courses.autowired.Address' available: expected single
matching bean but found 2: office,home
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating
bean with name 'employee': Unsatisfied dependency expressed through field
'address'; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying
bean of type 'com.naresh.it.courses.autowired.Address' available: expected single
matching bean but found 2: office,home

@Qualifier :

when we have more than one bean object for a Bean class, to specify which bean
Object should be injected out of many Bena Objects.

@Qualifier : will be used along with @Autowired annoation

@Qualifier annotaion will be confgigured with bean ID

Only Bean Objects should be invloved in DI.

Whenever Employee Object is Creted, By Default only offcie Address Should be


injected.
when no Qulifier provided, By Default only offcie Address Should be injected.

IE Qualifeir is Given then specifc Object Injecte.

Address:
home,

@Primary
office,

per

Case 1:
Employee:
// No Qulaifier : offcice should be injected
@Autowired
Address address;

Case 2:
Employee:
@Qulaifier("offcie") // Not providing any Qualifier
@Autowired
Address address; res should be injected

if(Qulaifier is avilable)

@Primary : Will be used to mark one bean Id configuration leavl, as a default


Bean Object out of multiple Bean configurations of same calss.

@Qualifier("home","office","perme")

Student s;
s = newStudet(), new Studnt();

Dependecy Injection via Interface:

=================================

Animal <Interface>

Impl Classess
Tiger implemntes Animal

Lion implements Animal

etc...

Zoo{

// Interface can hold Impl Class object

Animal animal; Tiger,LION

1 class with more than one Bean Object : @Autowired

1 interface with more than one Impl class.

Tyeps Of Dependecy Injection:


=============================
1. Filed/Property level Injection

Injecting Dependency by Propertylevel


Defining @Autowired on property/filed name

package com.dilip.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Employee {

private String empName;


private double salary;

// Dependency Obj.
//Field/property injection
@Autowired
private Address address;

public Employee() {
System.out.println("Employee Object Created");
}

public String getEmpName() {


return empName;
}

public void setEmpName(String empName) {


this.empName = empName;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

public Address getAddress() {


return address;
}

public void setAddress(Address address) {


System.out.println("This is Seeter method of Addres in Emplyee
class");
this.address = address;
}

2. setter Injection : Injecting Dependecy by Settter Method

First Obj. will created with default values

after, IOC conatiner calls Setter method will be called for


Dependecy Injection

w.r.to Annotations how to inject Dependecy Object via setters?

@Autowired at setter method level.

//Setter Injection

// Address: home,office:primary
//@Qualifier("offcie")
@Autowired
public void setAddress(Address address) {
System.out.println("This is Seeter method of Addres in Emplyee
class");
this.address = address;
}

3. Constructor Injection : Injecting Dependecy by Constructor

while Objection itself, we are injecting Dependecy in ISde


Object.

We have to define a constructor which accepts only Dependecy Objects.

@Autowired
public Employee(Address address, Organization org) {
this.org = org;
this.address = address;
}

Asssignment :

1. Qualifeir and Primary with Setter Injection


1. Qualifeir and Primary with Constructor Injection

Autowiring type :

Types of Autowiring:
====================
autowire : XML :

autowire = no ,
byName;
byType;
constructor;

autowire=byName

autowire = byType;

Address("address") {
}

address

Empl{

Address address;

autowire=constructor

Emp(Address adr){

Annoataions :

@Autowired

How @Autowired working with private variable?

==================================================

Spring Data Modules: =

====================

Spring Database Modules:

To perform DB opertions;

1. JDBC MOdule

will use JDBC API from Java lang.

Simplified the process of regular JDBC API Coding

2. JPA / ORM MODule

Spring JDBC Module:


===================
Request : Load data from Student

1. Select * from student;

JDBC :
Register Driver
Create Connection
Execute Query
Close Connection

JdbCTemplate: It is a predefined class.

JDbcTemaplte , provdiding Database environment to perform DB Operations

JDbcTemaplte, takes input of DataSource Details

jar files to be added: along with core jar files.

spring-jdbc.jar
spring-tx.jar

DB specific:
Oracle Db : ojdbc11.jar

Spring JDBC:

1. Configure Database Details


1. URL of Database
2. user name
3. passord
4. Driver

I am going to create Jdbctemplete Object

2. Insert Data into Student table:

3. Create a Pojo class aligned to out Student Table.

4. We have to wtite a class to perform DB operations/executing DB Queries

insert into student values(101,"ram",21);

update() from Jdbctemplate ,


update() will be used for insert/update/delete Queries

1. Please insert Data in side Employee


simlipfied version JDBC API

//Result rs = ps.execute(query)
ArrayList<Employee> list = new ArrayList();
while() {

Employee e= new Employee();


e.setEmpId(rs.get("eid"));
e.setEmpName(rs.get("name"));

list.add(e);

//with size 5 / Emp Objects

5 Places : Select Query of All emp ;

// Row Mapping
// Resultset to ArrayList of Emp Objects

ArrayList<Employee> list = new ArrayList();


while(rs.next()) {

Employee e= new Employee();


e.setEmpId(rs.get("eid"));
e.setEmpName(rs.get("name"));

list.add(e);

//with size 5 / Emp Objects

RowMapper :

Mapping Table rows to java Object from Result Set

RowMapper it's an interface

we should implemnt this row mapper

RowMapper conatins one abstartc method


mapRow()

impl to mapRow()

Spring JPA/ORM Module:


======================

JPA : Java/Jakarta Persistence API, from our Java lang JEE

jse : Core Java :


jee : Advanced java:

JAVA, JSE,JEE

Java Enterprise Edition : Jakatra Enterprise Edition


Java Persistence API

JEE:
java.sql : JDBC : DB interaction : DB operations
JPA is also from JEE: DB interaction : DB operations

1. JPA ?

API : Predefined Group of packages and collection classes and interface

JPA is an API which providing solutions of DB operations

JPA is a specification but not implementation.


JPA is a some rules and guidelines but not implemented solution.

JPA given predfiend interface but not implmented classes .

interface : we will define set of functionalities.


Classes : We will provide

with alone of JPA we can't perfom any DB operations.

based on JPA specifcation, we have to write solutions and those solutions we have
to use in our real time projects.

JPA :
interface calc{
add(int a, int b);
}

Third party :
Camel implements Calc{ casio implents calc{

add(int a, int b){


return a+b;
}

project

DilipCalc{

main(){

add(10,20); // 30
}
}

10+20=?

Real time project :

swiggy:

spring + JPA
****** you are not going to write solutions of JPA specification

ORM :

Object : Java : Entity classes


Relational : Database : Relational Database : Tables
Mapping : Mapping

conversion of Relational Records to Java objects

vice verssa : java objects to realtiona records

ORM Functionalities:
Spring JPA module

Maven :

Hibernate

-> spring - core moduels jar - 6


-> jdbc - 1
-> 2 jar
--> 2 jar

-> A jar file internally uses other jar file


-> A jar file depends on other file

1 jar :
refering other
+ add internal dependecy jar process

NO of Jar file

100% every real time projects will project mangement tools

Maven :

Project Management tool


-> Build of project
-> Compilation of source code (.Java file to .class)

-> Creates war/jar file


Primary Advantage of Maven :

-> importing/dowloading of project required jar files.

1. Create Project

2. Downlaoded some spring jar file --> Not allowed

Replace : Configuration in side maven of dependecy/required jar file with


version

Internally maven will downalod all jar file into your project

3. Buildpath configuration of jar file


-> Impl. Spring core module

Internal dependecy of Jars :


1 jar interanlly refering another jar

SIngle shot : it will downalod all jar files to project

Technical :

apchae :
MAven : we will create a xml file with name : pom.xml

POM : Project Object Model

pom.xml file, we are going to confgiure our required jar file.

Creation of Project

1. File -> create -> Maven Project


2. Provided details

Groupid : domain Id of Project / similar package name


artifcatId: Project Name

3. Finsih

Project is Ready.

pom.xml is created.
as part of pom.xml file, we are declaring required jar files of project.

Dependencies : jar file

to define jar files, Mavn provided a child tag called


<dependencies>

</dependencies>
spring-core-5.3.9.jar:

<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.9</version>
</dependency>

<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>23.2.0.0</version>
</dependency>

</dependencies>

Spring JPA ORM module :


======================

1. Create Maven Project


2. Identify Which jar files ae required for our project

Spring Core
Oracle driver
Spring jpa ORM
hibernate
3. Project setup is reday to for Programming

Requirement :

I want to insert/update/delete/select operatin on Order table

-> JPA Module with hibernate

1. Entity classes :

Entity class defined as Pojo class.

This is class representing a database table.

To define , entity classes we are unsing to use JPA annoations

@Entity
@Table
etc...
bY usning entity class we are achving ORM functionality.

How to write entiy class:


==========================

Table :

create table flipkart_orders(orderId number(10), productName varchar2(50),


totalAmount number(10,2));

Table Name : flipkart_orders


ORDERID NUMBER(10)
PRODUCTNAME VARCHAR2(50)
TOTALAMOUNT NUMBER(10,2)

1. Create a class

2. Please mark your your class with an annoation called as @Entity

PAYMENT_ID NUMBER(38) : long


ORDER_ID NUMBER(5) : int
EMAIL_ID VARCHAR2(255) : String
ORDER_COST NUMBER(10,2) : float
PAYMENT_STATUS VARCHAR2(50) : String

@Entity
@Table(name="payment_management") // DB table name
Class Payment{

@COlumn(name="" ) // Column Name of table


long paymanrId;

etc,,,

JPA Repository:
===============

Repository is representing DB operations on entity class.

SPring JPA :
Spring Provided 2 Pre Defined JPA reposototires:

1. CRUDRepository <Interface>
2. JPARepository <Interface>

Implentation:

Define Reposiotory:
We will create our own repository by extending Spring reposotories.

Reposotories are always wriiten as interfaces.

Every Table should contain Primary key:

CrudRepository<T, ID>

T : Tbale : Entity Class


ID : PrimaryKey column property datatype

Reposiory class:

--------------------

EntityManger:

db.properties
name=dilip
age=30
email=dilipsingh@gmail.com

JPA

Entity classes ->


Reposotories ->

by Using Reposotories , we are perfroming DB operation

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No


qualifying bean of type 'flipkart.entity.FlipakartOrderRepository' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

insert into flipkart_orders (productName,TOTALAMOUNT,orderId) values (?,?,?) :

In Spring JPA,

Internally TransactionManager uses

TransactionManager : Performing DB transactions

TransactionManager Requires
DB details

Spring JPA again provided a concept called as EntityManagerFactory


EntityManagerFactory
DB details
URL
USerNAme
password

Entity classes details to


base packges
Repositories Details
base Package of
Hibernate

JPA specification
Hibernate
Toplink
mybatis
ibatis..

TransactionManager :

"hibernate.hbm2ddl.auto", "validate"

validate : if table avilable Perfrom DB operation


if table not avilable throws exception table missing

update : if table avilable Perfrom DB operation


if table not avilable Creates the and Perfrom DB operation

create: For every execution , it will create table


if table avilable : Drop the table
and then it will create the table
Perfomring DB

create-drop: For every execution , it will create table

if table avilable : Drop the table


and then it will create the table
DB operation
while terminating execution immedialtely jpa will drop the tbale

@Entity
@Table(name = "flipkart_orders")
public class FlipakartOrder {

@Id
@Column(name = "orderId") // Primary key column
private Long orderID;

@Column(name = "productName")
private String productName;

@Column(name = "TOTALAMOUNT")
private double totalAmount;

update :
create table flipkart_orders(orderId number(222) primary key, productName
vartchar2(256) , totalAmount number(10,9));

Req: delete All reords:

Req: Insert Data into product Tbale

1. One time Setup


2. entity classes
3. Reposotories

Order

15 differnwet DB opertaions on the Order table

1. create tabale in DB
crete entity
2. Create entity
Crete tbale

Spring JPA Module Project Setup Complted.

1. Patient
Information

emailID
Name
Age
Gender
Contact

1. Add Single Details


Add More than One Patient Details
2. Update Details
old value :
+828388
update patient set mobilenumber=98886336 where id =abc@gmail.com
3. slect Patient Details
pid
based on column names
4. delete

C - Create : Insert Operation


R - Read : Select Operation
U - Update : Update Opertion
D - Delete : Delete Operatios

Create tbale
from the tbale we will entity class

Tbale -> Entity

CREATE TABLE "C##DILIP"."STUDENT"


( "SID" NUMBER(10,0),
"NAME" VARCHAR2(50 BYTE),
"AGE" NUMBER(3,0)
)

@Entity
@Table
public class StudentDetails{

@Column
int sid

// column name = property name


@Column (name="name")
String sname
@Column (name="age")
string studentAge;

1. Select Based on Email ID

select * from patient where emailid='abc@gmail.com'

findBy() JPA : for non primarykey columns


1. Defeine abstarct method with below synatx in reposioty

findBy<Property Name of Column>(value)


2. Abstarct method shuld be called from repository Instance

data based on gender


is it PK?
if yes : findById(); // No need to defein in our Repository interface
NO :
1. Defeine abstarct method with below synatx in reposioty

findBy<Property Name of Column>(value)

1. Get Data based on age and Gender

age 36
gnder FEMALE

@Column
private int age;

@Column
private String gender;

select * from patient where age=? and gender=?

List<Patient> findByAgeAndGender(int age, String gender);

getPateintsWithAgeandgender(30, "FEMALE");

JPQL :

Native SQL :
select * from Pateint

1. Create Project
2. SPring JPA Configuration
3. Entity class
4. repository
5. DB operations class

Defining Native SQL Query:


============================
select * from patient where emailid=?

1. Define a method in side Repository.


2. We should provide sql query on top od method withan annoation called @Query
3. Aa part of @Query, we should provide our sql query to the attribute value. and
we should provide nativeQuery attribute value as true.

2. Get Details by using emailId:

select * from patient where emailid=......

1. Define a method in side Repository.


2. We should provide sql query on top od method withan annoation called @Query
3. Aa part of @Query, we should provide our sql query to the attribute value. and
we should provide nativeQuery attribute value as true.

1. Index Based Query Parameters

2. Named Query parameters

1. Index Based Query Parameters

Syntax: ?<index Number>


ex: ?1

NOTE : index starts always from 1


select * from patient where emailid=?1 and

3. Req :

select * from patient where age=30 and gender='MALE'

select * from patient where age=?1 and gender=?2

1. Define a method in side Repository.


2. We should provide sql query on top od method withan annoation called @Query
3. Aa part of @Query, we should provide our sql query to the attribute value. and
we should provide nativeQuery attribute value as true.

Named PArameters :

INSERT INTO patient VALUES ('dilip@gmail.com',31,'+9188882828','MALE', 'Dilip


Singh')

INSERT INTO patient VALUES (?,?,?,?,?)

syntax :
:nameofparameter

@Param:

Assignments :

1. DML Operations w.r.to

native SQL Queies

insert
update
delete

JPQL : Jakarta Peristence Query Language

It is simlar to SQL language

This JPQL defines Queries w.r.to. Entity Classes

select name from patient;


Spring MVC/Web module :
=======================

This a module for creating Web applications with Spring FW.

This is implemented on Servlet API

M - Model
V - View
C - Controller

MVC - ?

View : This is representing all UI logic


From the view Layer Request will triggered

Controller :
Controller Layer is responsible for receving Request from View Layer.

Controller layer responsibility should forwarding request data to the Model


Layer.

Controller layer should not handle business logic.

business logic should be handled by Model Layer.

ICICI
: Calcuation of Loas intrest
How much u want ? 1000000
12%
60

Spring Web Application Setup :

===============================

1. Create Dynamic Web Project in eclipse


2. Convert it to Maven paroject
Right Click on Project
Configure
Maven Project

3. Add Dependencies to pom.xml

<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.29</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>

</dependencies>

4. Configuration Class

Create Confgi class by extending WebMvcConfigurationSupport

5. Spring Web initilizer

String[] allowedURLMapping = {"/"};

6. Test Controller :

localhost:8080/spring-mvc-app/hello

Internal Workflow of Spring MVC:


==================================

http://localhost:8080/spring-mvc-app/login

http://localhost:8080/spring-mvc-app/register

http://localhost:8080/spring-mvc-app/operations

Front Controller Design Pattern :

DispatcherServlet

1. In Spring Mvc , Controller Classses

Annotated with @Controller

2. Now We can create URI's in side controller classess.

HTTP method GET

@RequestMapping("/register")
@ResponseBody
public String userRegister() {
return "User Registartion Succeesfull";
}

whenever we are deploying Project, Spring MVC Module internally scans all
@Controller classes
Spring MVC , Scans all URI methods and creates Handler Mappings for very URI

when client triggers Request with /login , thi swill be landed on DispatcherServlet

NOW DS cheks inside Handler mmapings is there any URL avliable with /login

Endpoint Methods:

URI

@RequestMapping("/register") //UserController::userRegister
@ResponseBody
public String userRegister() {
return "User Registartion Succeesfull";
}

//POST
@RequestMapping("/login") //UserController::userLogin
@ResponseBody
public String userLogin() {
return "User Login Succeesfull";
}

//PUT
@RequestMapping("/operations")
@ResponseBody
public String userOperations() {
return "User Operations Succeesfull";
}

1. How to define Controller class?

Define a class and mark with @Controller

2. Defining URI methods

Endpoints:
1. Idenitfy which HTTP method should be Defines in side BAckend.

How do select HTPP method?

Req :

1. 10 URI :
1. createion user
2. Delet user
3. Update User Data
4. login USer
5. get user data
6. update User Addresss
7. adding New Address
8. Delete address
9. Add Card Detsils
10. GetProduct Details

C - Create - Insert Operation


R - Read - Select Query
U - Update - Update Query
D - Delete - Delete Query

HTTP:
GET - Used fro Reading/Getting/fetching Data opeartions
POST - USed for Creation/Adding Operations
PUT - Used for Updating Data Operations
DELETE - Used for Delete Operations

C - Create - Insert Operation : POST


R - Read - Select Query : GET
U - Update - Update Query : PUT
D - Delete - Delete Query : DELETE

1. createion user : POST


2. Delete user : DELETE
3. Update User Data : PUT
4. login USer : POSt
5. get user data : GET
6. update User Addresss : PUT
7. adding New Address : POST
8. Delete address : DELETE
9. Add Card Detsils : POST
10. GetProduct Details : GET

@RequestMapping :

Request + Mapping Request from UI


This annoation represents what type of Request HTTP method
and
URI information
and
Request Data Format

POST UI ---------> Spring MVC


/create

1. If we define only URI . then by default it is a HTTP GET method

If you define @Controller in class level, URI method must should have
@ResponseBody
2. @RestController = @Controller + @ResponseBody

http://localhost:8080/spring-mvc-app/order POST

3. Can I define same URI with in same controller or Other Controller?

Yes, But difference should in HTTP methods

4.

Name = Additionla Explantion


path= URI value
method= Define Whihc HTTP method
value= Alias to Path

Short Cut Annotations of @RequestMapping

@GetMapping
@DeleteMapping

http://localhost:8080/spring-mvc-app/order/update
http://localhost:8080/spring-mvc-app/order/load
http://localhost:8080/spring-mvc-app/order/get/all

http://localhost:8080/spring-mvc-app/user/add
http://localhost:8080/spring-mvc-app/user/delete
http://localhost:8080/spring-mvc-app/user/update

JSP pages :
==========

WelCome Message : Welcome to Spring View Layer

View Resolver:
================

View : JSP files :

This is component which responsible for resloving view names jsp file names.

Configure View Resolver w.r.to JPS files loacted folder

1. Configruing View Resolver


// PATH of Folder
// .jsp

2. @Controller : Invoke JSP fie from URI method


Now should not use @ResponseBody
3. Model Parameter

1. Assignmnet:

Reigister User

First Name
Last Name
Gender
Age
Qualification
Marks
DOB

SoAP: simple Object Access protocol

XML : Protocol

Http + XML =

REST Services :

=================

1. Representational State Transfer

2. REST Services are follwoing HTTP protocol

https://infinity.icicibank.com/corp/AuthenticationController?
FORMSGROUP_ID__=AuthenticationFG&__START_TRAN_FLAG__=Y&FG_BUTTONS__=LOAD&ACTION.LOA
D=Y&AuthenticationFG.LOGIN_FLAG=1&BANK_ID=ICI&CTA_FLAG=DEPOSIT&ITM=nli_cms_FD_HPDes
ktop_FDIndependenceDay_OpenFDNow_btn&_gl=1*15zgwo8*_ga*MzQyOTMyMzYuMTYzMDQyMjkwMw..
*_ga_SKB78GHTFV*MTYzNzE0MTQ1NC43NC4wLjE2MzcxNDE0NjIuNTI.&_ga=2.57708330.1465037206.
1692371865-1095177735.1679107897

Spring MVC + JSON :


=====================
1. Crete Spring MVC Project

JSON:

=====
Java Script Object Notation

Data Format / Text Format

XML Data Fromat :


Student
id
name
marks
<Data>
<Student>
<id>1</id>
<name>Dilip</name>
<marks>100</marks>
</Student>

<Student>
<id>2</id>
<name>Laxmi</name>
<marks>333</marks>
</Student>
</Data>

JSON :
key value pairs Data
key:Value
name: Dilip

1. Data is Derived in key/value pairs


Keys should be in double quotes always
Values :

If value is Numeric then no need of Double Quotes


If value is Not Numeric then need of Double Quotes

2. Data is Separated by commas


3. Curly Braces will holds Data/Objects
4. In JSON Square Braces [] , will represent array/list of value

Ex : Student

{
"id":1,
"name":"Dilip",
"marks": 333.99,
"isSelected" : false
}

List of Students Data


{
"Students" : [

{
"id":1,
"name":"Dilip",
"marks": 333.99,
"isSelected" : false
},
{
"id":1,
"name":"Dilip",
"marks": 333.99,
"isSelected" : false
},
{
"id":1,
"name":"Dilip",
"marks": 333.99,
"isSelected" : false
}

]
}

====================

{
"name" : "Dilip",
"email" : "dilip@gmail.com",
"mobile" : "+91 73777373",
"password" : "Dilip123"
}

To support JSON Data Format in Spring MVC , we should add Some Dependecies

Convertion from JSON data fromat to Equivlant Java Object.

Convertion from JAVA Object to Equivlant JSON Data Format.

Devloper :

adding jar files which are resposible for Conversion from JAVA to JSON
and vice versa.

1. Jackson API jar fles


2. GSON API

Please addd below 3 jar dependecies

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.15.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.15.2</version>
</dependency>
Post Man:

Add requet
Select HTTP method
enter URL
Select BOdy
raw
JSON

id:1234
name:dilip
avgMarks:78.77

2. Get single User Details


Response as JSON Data

{
"name": "Dilip Singh",
"email": "Dilip@gmail.com",
"mobile": "7237237",
"password": "Dilip123"
}

3. Get all User Details

List of Java Objects to JSON ARRy

[
{
"name": "Dilip Singh",
"email": "Dilip@gmail.com",
"mobile": "7237237",
"password": "Dilip123"
},

{
"name": "Suresh Singh",
"email": "Suresh@gmail.com",
"mobile": "333",
"password": "Suresh123"
},
{
"name": "Naresh Singh",
"email": "Naresh@gmail.com",
"mobile": "34343",
"password": "Naresh123"
}
]

4. s part of Request sedning JSON arry

Request:
[
{
"name": "Dilip Singh",
"email": "Dilip@gmail.com",
"mobile": "7237237",
"password": "Dilip123"
},

{
"name": "Suresh Singh",
"email": "Suresh@gmail.com",
"mobile": "333",
"password": "Suresh123"
},
{
"name": "Naresh Singh",
"email": "Naresh@gmail.com",
"mobile": "34343",
"password": "Naresh123"
}
]

=========================

Repository Layer:
====================

<!--Spring JPA jar files -->


<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>21.9.0.0</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.9.Final</version>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>

1. Create Spring Jpa Configuration class

swiggy_users

"name": "Dilip",
"email": "aaa@gmail.com",
"mobile": "+91 73777373",
"password": "Dilip123"

4 columns :
name : String
email : String
mobile : String
password : String

--> Repository Layer Creeation

Autowired with Service layer

Path Variables:
===============

Get single User Details based emailID

10 products : order1234567
Get Order Details based on OrderId:
order1234567 :

Path Varibales a template varibale as well as called as place holder of an URI.

/user/fetch/{emailID}
/user/fetch/dilip@gmail.com

http://localhost:8080/swiggy/user/get/{emailId}

http://localhost:8080/swiggy/user/get/Dilip@gmail.com

Req :

swiggy_order
orderID
orderstatus
amount
emailId
city

Req 1 : Adding Order Details

Req 2: Get Ordr Details based on


email
and
orderStaus
email=dilip@gmail.com
orderStaus=CANCELLED

Query String and Query Parameters:


===================================

Query String : Groop of Query parameters


Query Parameter : Key-value , passing information as aprt of URL

Each and Every Individual Query parameter should be Separtaed by &

Passing data/information to Server


list of users : city is Hyd age is 30
localhost:8000/swiggy/user/city/Hyderbad

localhost:8000/swiggy/user/get?city=Hyderabad&gender=male

Gender Male Coustomeres

gender
male , female
city
Bang.pune

Contrroller :
Logic

Transfer to Service layer

@RequestParam is Query Parameter

Path Varibale Vs Query Param

/user/get/city/{city}/age/{age}

get Users By City

1000 Users

Req : I want user belongs to eith city is Hyd or


age=25

city: Hyd

age=25

will not pass both

https://www.flipkart.com/mobile-phones-store?fm=neo
%2Fmerchandising&iid=M_033281d6-a020-4759-b9b5-
58a84c3f26ea_1_372UD5BXDFYS_MC.ZRQ4DKH28K8J&otracker=hp_rich_navigation_2_1.navigat
ionCard.RICH_NAVIGATION_Mobiles_ZRQ4DKH28K8J&otracker1=hp_rich_navigation_PINNED_ne
o%2Fmerchandising_NA_NAV_EXPANDABLE_navigationCard_cc_2_L0_view-
all&cid=ZRQ4DKH28K8J

https://www.flipkart.com/television-store?otracker=nmenu_sub_TVs%20and
%20Appliances_0_Televisions&otracker=nmenu_sub_TVs%20%26%20Appliances_0_Television

flipkart/products/tv

all Brans TVS and all sizes and all rpices

https://www.flipkart.com/search?sid=czl&otracker=CLP_Filters&p%5B
%5D=facets.brand%255B%255D%3DMi

select * from tv where brnad=mI

https://www.flipkart.com/search?sid=czl&otracker=CLP_Filters&p%5B
%5D=facets.brand%255B%255D%3DMi&p%5B%5D=facets.screen_size%255B%255D%3D48%2B-
%2B55%2Binch

select * from tv where brnad=mI and inch =55

https://www.flipkart.com/search?sid=czl&otracker=CLP_Filters&p%5B
%5D=facets.screen_size%255B%255D%3D48%2B-%2B55%2Binch&p%5B%5D=facets.brand%255B
%255D%3DMi&p%5B%5D=facets.operating_system%255B%255D%3DAndroid

select * from tv where brnad=mI and inch =55 and osandroid

HTTP Status Codes:


==================

On Successfull Request execution : 200

Invalid URI/URL : 404 Not found

Whne Server can't execute Request successfully that means

unable to produce expected Response


500 Internal Server Error.

HTTP status codes are 3 digit numbers, prodcued by web server as part of
response.

Status codes represent client Request execution status.

These codes represents outcome of Request that menas status of coomunication b/w
cleint server.
Status code are part of HTTP protocol.

status code are grouped into 5 categories


=======================================

1xx : Informational Status codes: HTTP protocol Information

2XX : Success staus of execution : Cleint Request are processed succeffuly.


3XX : Redirection Status Codes : CLient should ReDirect request to complete
Successfully.

4XX: Cleint Sode Errors : Exposing Cleint Side Data problems or errors.

5XX: Server Error: Exposing Server Side problems or errors while executing Cleint
Requests.

1xx : Informational Status codes: HTTP protocol Information level

100 Continue :

101 : Switching B/W protoclos

HTTP -> SMTP

102 : Proccessing

2XX : indicates Successfull processing of Request.

200 Ok: Request executed Successfully, Reposne Successfully.

201 Created:

Request is executed Succssfully and a new Resource is created.

New Record is Genearted in DB

insert Query is executed succesfully.

A per REST Serivces implmentation, 201 Created.

204 No Content :

wilson@gmail.com

ResponseEntity:
===============
Response+Entity

Whole Response Data:


Sttaus Codes
Response Body
HTTP Headers

Headers part of Request and Response :

Communicating Two application : Rest Services Integration

XML

HTTP Headers :

================

HTTP Headers are part of HTTP Protocol.

Headers will be used to exachange information between and cleint and server along
with Request and Response Data.

what information:
Content Type of Request and Resoonse
Cookies
Authentication
and
Authorization

RestServices/API Integration/Communication
==========================-====

Producer : API provider

Consumer : API Integrated Application

//Call flikart REST Service


//http://localhost:8080/flipkart/track/payment/payment123456
//GET

Response :
{
"paymentID": "payment123456",
"payamentStaus": "Suucess",
"paymentDate": "2023-09-01"
}

1. Be ready with URL


2. Created Response
3. How To call FLip kart Rest service?

RestTemplate :

We are consuming REST service of opponent application

XML Response/Request:

Security Module:

XML Data Format in Request and Resppnse of RETS API:


=====================================================

As part of Request Body :


=========================
Content-Type : Request body data format type xml/json

public class UserAccountData {

private String gmailId;


private String fullName;
private int defaultMemoryInGB;

XML Data Payload :

<UserAccountData>
<gmailId>dilip@gmail.com</gmailId>
<fullName>DilipSIngh</fullName>
<defaultMemoryInGB>15</defaultMemoryInGB>
</UserAccountData>

Response :
============
accept:application/json

I want Response data in JSON fromat

accept:application/xml
I want Response data in XML fromat

Spring Security:
================

Security :

To protect our web application/data of our aapplication from external Resources.


Authentication:
Who are you ?
Valid user

Authorization:
What you are?

NareshIt :

Studentds
limitations
Registering
Allowed access only Training
Trainer
limittations
I can access all Stduents of my Training
I am passing some rules to Students

Admin
limitation
Pass Rules to Students and Trainers

Trainer : Connected NareshIt:


Authenticated

Authrization:
Students imformation as prt of your training

Gmail :
dilip@gmail.com
dilip123

How to enable Security in Web Application:

satteless vs Statefull :

JWT token based :


JWT token?

1. Speing Web MVC + JPA


2. Add Security Dependecies to Project
3. Security Layer Implmentation.

JWT :
How to genarate tokens
validate Tokens

Stateless vs Statefull:
---------------------------

JWT : JSON Web token

JWT is a open industry standard to share information b/w two resources like

cleint and server

To genarte JWT will conatins 3 parts :

Header
: Singing Algorithm being used to genarte a token

Payload :

User Name

Signature : Cryptographic algorithom

JWT jar :

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
</dependency>

1. Creation of Token
2. Valiadation of Token
is It Correct UserName or not?
is It Expired or Not

You might also like