0% found this document useful (0 votes)
11 views

SpringBoot-MS-Dec-07

The document provides an overview of Spring Boot and Microservices, detailing the principles of Dependency Injection (DI) and Inversion of Control (IoC) within the Spring Framework. It discusses various configurations for setting up Spring applications, including XML and Java-based configurations, and explains the differences between Setter Injection and Constructor Injection. Additionally, it covers bean wiring, scopes, and the singleton design pattern in the context of Spring applications.

Uploaded by

Saim Keshri
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)
11 views

SpringBoot-MS-Dec-07

The document provides an overview of Spring Boot and Microservices, detailing the principles of Dependency Injection (DI) and Inversion of Control (IoC) within the Spring Framework. It discusses various configurations for setting up Spring applications, including XML and Java-based configurations, and explains the differences between Setter Injection and Constructor Injection. Additionally, it covers bean wiring, scopes, and the singleton design pattern in the context of Spring applications.

Uploaded by

Saim Keshri
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/ 32

Welcome to Spring Boot And Micro Services:

Dilip Singh

11 years
Still I am working
Java Devloper
Java : Spring < Spring Boot , MicroServices

Demo:

100 % Every rela time project will use a framework

1. FW: not eligible for the job

Java : Spring FW

SpringBoot + MicroServices ?

Spring Boot & MicroServices @ 9:00 AM (IST) By Mr. Dileep Singh


Day-1 https://youtu.be/HPsq8dm24F4
9154861173

Spring Boot & MicroServices @ 9:00 AM (IST) By Mr. Dileep Singh


Day-1 https://youtu.be/HPsq8dm24F4
Day-2 https://youtu.be/WBJQXpMQa64

Spring Boot : Training

Spring FW :
Spring Boot : 100 % both are same w.r.to Logic/Progrmaing

Spring / Spring Boot : alomost equal

Working: 60 Micro Services : One Projects


Spring FW:
----------

Spring FW : 2003 : Rod Jhonson & Team

Current Versions:
=================

Spring Core Module:


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

Spring FW : Spring 6

Advantages:
----------

1. Dependecy Injection & IOC(Inversion of Control) Principle

IOC : This is a principle to achive Dependency Injection.

Spring FW internally by usinf IOC is used to manage instances and


dependncies between Instances/Objects as part of Application.

Dependency Injection :

Spring FW by Using IOC Concept, Injects the the dependncies at Runtime of


application.

//Emp depends on Address?

Core Java :
---------

DI :

Dependency is Address:
injected into Employye.

1. Defeine Address class


2. Create Address Object
Address companyAddress = new Address();
3. Define Employye class with Address
4. Inject/Pass Address object to Employye Object.
Spring :
------

1. Define Your classess

Addreess.java

package co.dilip;

public class Address {

String city;
int pincode;

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public int getPincode() {


return pincode;
}

public void setPincode(int pincode) {


this.pincode = pincode;
}

--> Pass Class information to Spring FW , so that Spring Will create Objects
for Address class and maintined that object by SPring FW.

--> Define Employye class :

package co.dilip;

public class Employyye {

String name;
int id;

//Dependecy Of Address Object


Address address;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public Address getAddress() {


return address;
}

public void setAddress(Address address) {


this.address = address;
}

--> Pass information of your calss, as well as which Object you are having
dependency provide that information also to Spring FW. So that, SPring will inject
that dependecy Object into Curent Object.

Address-> Injected into Employye.

Spring Boot & MicroServices @ 9:00 AM (IST) By Mr. Dileep Singh


Day-1 https://youtu.be/HPsq8dm24F4
Day-2 https://youtu.be/WBJQXpMQa64
Day-3 https://youtu.be/3WqwrdbD3IU

(Inversion of Control) :

Inversion of Control

Inversion : Opposite/reverse
Controle : Managing

Spring Core Module Project :

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

1. Create a Java Project

2. Is this Project supports by default Spring Functionality?

No

Add Spring Core Module jar files


3. Spring Core Module Setup complted.

4. Create java classes

Address
Student

5. Configure details of class with Spring FW

1. XML Configuration

2. Java/Annotation Based Configuration

1. XML Configuration:

Java classes informationwe are confuguring by using a XMl file.

Spring FW defined some rules to configure java classes

1. Create XMl file

2. we ahve to define a parent tag called as


<beans>

3. Confgiure java class information with chil tag called as <bean>

Address {

f}

Address comapny = new Address();

Object Name/ Instance Name / Object Id/ Reference : company


Class : Address

6. Create Spring Container Object and by passing XML file details

7.

SPring Container can be created by using 2 ways


1. BeanFactory <I>
2. ApplicationContext <I>

1. Spring Intro :
Spring FW will create Objects for the Classes.

when we provided class infor mation to Spring via Configuration, then only Spring
FW will create objects and mnages the Object.

I don't want an object created for a class by Spring FW. :


Don't provide information of those calles to Spring FW
Don't configure in XML file.

Bean Id : OBject Ref. as part of Spring Continer

1. If I given wrong bean Id to Continer what will happens?

Exception in thread "main"


org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named
'XYZ' available

2. How many Bean Objects can be cretaed for a Bean class?

Core Java : How many Objects can be cretaed for a class?


many

Address company = new Address();


Address office = new Address();
Address home = new Address();
etc..

Address company = new Address();


company.setCity(BANG)

Address a = new Address(Bang,8890); city=Bang


pincode=88900

Spring : How many Bean Objects can be cretaed for a Bean class?
many

<bean id="company" class="com.spring.core.demo.Address"> </bean>


<bean id="home" class="com.spring.core.demo.Address"> </bean>
<bean id="offcie" class="com.spring.core.demo.Address"> </bean>

Spring Boot & MicroServices @ 9:00 AM (IST) By Mr. Dileep Singh


Day-1 https://youtu.be/HPsq8dm24F4
Day-2 https://youtu.be/WBJQXpMQa64
Day-3 https://youtu.be/3WqwrdbD3IU
Day-4 https://youtu.be/XUksbXOlHBs
Day-5 https://youtu.be/IZkGr3KjkOw
Day-6 https://youtu.be/5sI8txqc2GI
Day-7 https://youtu.be/AQElemZw3qg
Dependency Injection:
=====================
bY using Dependecy Injection we can inject any type of data in side an Object.

1. Setter Injection:

Spring Conatiner will inject data/values/objects into propeties with the


help of Setter methods in a Spring Bean class.

To achive Setter DI we need to define setter methods for those properties.

IN XML , Spring Provided a child tag for <bean> called as <property>

Rule :
1. To achive Setter injection, we should define always a default
constructor.
2. We should define setter methods always

<beans>
<bean id="student1" class="com.dilip.spring.di.Student">
<!-- id : 100 , name: DIlip , avg : 88.00 -->
<property name="studentId" value="101"></property>
<property name="studentName" value="Dilip Singh"></property>
<property name="avgOfMarks" value="88.00"></property>
</bean>
</beans>

Can I write multiple Student Object with different data?

1. What Type of Data we are injecting ?

Data Types :

Primitive : Wrapper Cllases

8 Data Types
Wrapper Cllases : 8 primitive
<property name value>
int long short byte double long char boolean

Assignment : short, byte , long , float :

Non-Primitive:

String
<property name value>

Collection Data Types

List : will allow duplicates


String
Double
Assignment : 7 Data Types

<property name >


<list>
<value>
Set : Not allow duplicates
<value>HotelOne</value>
<value>HotelTwo</value>
<value>HotelThree</value>
<value>HotelFour</value>
<value>HotelFive</value>
<value>HotelFive</value>
Assignment : 8 Primitiev Data Types

Map:

Map :
key-value

a key-value pair will be called an entry

private Map<String, Double> itemPrices;

Assignmemnts :

Map<Integer, String>
sid, name
Map<Long,String>

Mobile , Names

Non-Primitive:

User Defined Classes


Classes which are devloped by us : Developeres

Employye
Student
Swiggy Order
Adress.
.....

References of Classes:

PreDefined Classes : Built In clasess : Calles which are already


implmented and provided by Lang
Java, Spring

DI can be achived only between Bean Objects.

ref : this attribute will be used to refer another Bean Object which has to be
injected.

value should bean id of Dependency Object


Req : Create 100 Customer Objects, and every customer should belongs to company.

Core : 100 Addresss Objects

500072
HYD
TS

: 100 Customers

Spring :
1 Bean Object : Address

100 : Customer : 1 Address

Customer:

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

2. Constructor Injection:

CI is part of DI.
DI injection will hapens via constructors of the Bean calsses

How to Configures CI in Bean?

to configure CI, spring provided a child tag <constructor-arg> as part of


<bean> tag.

Rules :
1. while defining <constructor-arg> values we should follw an order of
Constructor Parmas Order

2. In case if we don't want ot follow order of values hten we should take


help of an attribute called as "index"

with this we will define index order of Constructor Params postions

3. For example , I would like to inject only Id and Name , don't want price
Not Posiible, We should pass 3 values 100%

// App Params Constructor


public Product(int productId, String productName, double price) {
super();
System.out.println("Product All PArams Constructor Excuted");
this.productId = productId;
this.productName = productName;
this.price = price;
}

public Product(int productId, String productName) {


super();
System.out.println("Product All PArams Constructor Excuted");
this.productId = productId;
this.productName = productName;

new Product(1,"vall");

new product(); // Not valid : No Default Constrcutor

public Product() {

}
new Product(1); // 1 value : 3 values expecyed
public Product(int pid) {

}
new Product(1, "phone"); // 2 value :
public Product(int pid) {

new Product(1,null, 37777.00); // Valid One

4. IN the current Product class, I would like to add a functionality which


should take id and name always but not price. Spring CI.

1. Write class, with properties : id name and price

REq : please write functionality, when I created Object only id value must
be assigned.

public Product(int pid) {

REq : please write functionality, when I created Object id and name values
must be assigned.
public Product(int pid, String name) {

I don;t want to pass initilize values,

public Product() {

new Product();

Req : where may initilize or may not .

Question : The current Product class is eligible for Setter Injecction or not?
Eligible,

SI : defuelt Constrctor , setter methods


CI : Yes, 3 params, 2 params

Req : Write a class,

where i can inject any value of property any time for any bean Object.

0 values :
<bean id="mouse" class="com.naresh.spring.di.ci.Product">

</bean>

1 value : id
<bean id="mouse" class="com.naresh.spring.di.ci.Product">
<property name="productId" value="6677"></property>
</bean>
1 value : price
<bean id="mouse" class="com.naresh.spring.di.ci.Product">
<property name="price" value="6677"></property>
</bean>
3 values : id name price
<bean id="mouse" class="com.naresh.spring.di.ci.Product">
<property name="productId" value="6677"></property>
<property name="productName" value="Dell Mouse"></property>
property name="price" value="2444"></property>
</bean>

1. In SI, is it mandatory to provide all property values of a Bean Object?

No, Partial data/properties

2. In CI, is it mandatory to provide all property values of a Bean Object?

3 : Param : 100% : 3 values


: 1, null, 0.0
2 : Param : 100%v : 2 values : 1, null

CI : Complete Data Injection


SI : Partial Data Injection

Req : whch should take all property values every time :

Req : where i can inject any value of property any time for any bean

Diff B/W SI and CI?


Best out of SI and CI
Assignement:
other int,double : try other 6 primitives

// Multiple Constructors in same calls

Collection Data Types:

List :
Assignment :

Set and Map


Define Other classes :

Non-Primitives :

Other calss Objects / References of Other calsses:

SI : <property ref="otherBeanID">
1. Objecte will be created with Default Construcotr
2. defaault values for all properties of an Object;
3. Depends on <property> , setter methods

CI :
1. Object will be created always by using parameterized Constructor
2. Properteis oB Object will be initilized at the time Object creation
3. 100% passing all values for constructor

Hi Sir, earlier we have not used default constructor for setter methods still its
working & currently we are recommended to use default constructor with setter
methods.

// Wriiten No Constructor ,: JAva compiler will add a empty default Constructor

// Wriiten a construcotr with params:


Bean Wiring:
------------

Bean Wiring , connecting bean Objects.

One Bean Object is referenced/connected with another Bean Object

Assignment :

Product{

OrderDetails{

Product

public class Cart {

private int noItems;


private OrderDetails details;

//Setters //Construcotrs
}

Bean Scopes:
------------

scope: limit, Accesbility

Bean Scopes:
-----------

A scope Defines visbility/accessbility and lifecycle of a bean Object when we are


running ourSpring Application.

when Spring Conatiner created the Bean Object, Once Bean Objects are created By
Conatiner, Conatiner will provide a scope for that bean Objects.

Spring Framework Provided 5 bean Object scopes:

To configure bean different beans scope, we need to take help of an attribute


"scope" inside <bean> tag.

When we are not defined any scope , interanlly Spring will conside
scope=singleton
1. singleton:

This is the default scope for every Bean Object crreated By Conatiner.

When A bean Object scope is singelton, Whenevr we are getting/requesting


bean Object from Spring Cotainer, Spring Conatiner will returns same Object always.

That mean, for every bean Object Configuration, Spring Conatiner creating
bean Object, and Spring maintianing that Object as a singleton Object.

ApplicationContect container = new FSXAC(xml);

Employye
Product

container.getBean();

getBean();

Signleton Design Pattern:


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

As per Singleton DP class, only one Object has to be avilable for that class
in entire application memorly level.

Q: How to implement Singleton, functionlaity of singleton DP:

2. prototype

Whenever We are getting Bean Object from Container, Conatiner will create and
return always a new Object with configuration values.

Req: I would like to get every time new Object from Container:

Web Application Functionalites :

3. request:
Many Requests
For evry new HTTP request from FE, a new Bean Object wil be created by
Conatiner.

4. session:

maintinaing data accorss multiple requests

HpptSession

foe evry HttpSession Object creation, Spring will create new Bean
Object assocuted to Http Session.

5. application/global-session
across mupltile sessionss , if we wan to sahre some information,

I can't show you prctically now

Spring Boot:
============

Spring Boot is a wrapper framwework on top of Spring FW

Spring FW

Then Only We can inderstand Spring Boot

Spring Boot :
Spring FW
-> Add on features of Spring Boot.

minimum fuss:

Most Spring Boot applications need minimal Spring configuration.

By Using Spring Boot , again we are creating Spring applications.

Automatically configure Spring and 3rd party libraries whenever possible

Absolutely no code generation and no requirement for XML configuration

Annotation Based /Java

Spring Core Project :

1. Create Java Project


2. Downlaod Spring FW jar files : 20 jar fle
3, Configure jar files of Spring Core to our project
4. Start writing code

Spring Boot enables Rapaid Application Devlopment of SPring applications

Maven :

What is Maven ?

Maven is a Project Management Tool

Maven is used in Java Projects, to define dependecies of a project

Maven is used for building an application/Project


Maven is called Build Managemnt Tool.

1. Create Java Project


2.. Configure to Maven Project

a new file called as pom.xml created inside project.

pom.xml

pom : Project Object Model

pom.xml is key file w.r.to Maven

How to Configure jar file / dependecies details in pom.xml

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

Maven is tool/software :

we should follow maven rules and regulations

5 jar files

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

</dependencies>

JDBC :
oracle

Maven Projects always conatins target folder:

target : target folder will conatins all compiled .calls and as well as war file
jar files

Maven goals :
clean : it will clean all .class files from project .java

TBD : Provide opinionated 'starter'

1. Create Java Project


2. Configure jar files
Spring : 2003

Spring Boot:
------------

Released in 2014 Spring Boot 1


Spring 4
Spring Boot 2
Spring 5
Spring Boot 3
Spring 6 Java 17 >

Creation Of Project :

1. Spring Initilizer Portal

https://start.spring.io/

2. From IDE's
Eclipse
+ Install aplugin called as Spring tools Plugin
IntelliJ
Eclipse + plugins related Spring Boot = STS : Spring Tool Suite

https://spring.io/tools/

spring-tool-suite-4-4.21.0.RELEASE-e4.30.0-win32.win32.x86_64.self-
extracting.jar

Double click on jar file


make sure Your system is installed with Java and configuered Variables.

STS:

File -> New -> Spring Starter Project

Spring Boot application always integrated with Build tool : Maven/Gradel

Maven :

Project Metadata :

Group : Domain Name of Project


Artifact : Project Name
Name : Project Name
Package name : Domain Name + app name
After Project genearted and extract it from zip
import in eclipse :
import -> Maven -> Import Mavne Projects

Snapshot : 3.21.snapshot : It's in Progress,

1. Are you added any jar files information mnaullay to your project ?
No
2. Logic wise , is it Spring or not?

annoataion based config:

Spring Boot Core Module:


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

1. I will take examples of Setter and Constrcuotr Injection with Properties

starter : Starter is group of Dependecies of Spring FW defeined inside pom.xml

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId> Core Module
</dependency>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> JPA Module
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> Web Module
</dependency>

<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Assignment-
-----------

Student

College

1. Primitives
String
References
Collection
List
Set
Map

SI
CI
Scopes

Annoatation Bassed Configuration :


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

Now we are creating bean calsses and Objects with help Java Annoataions

50 > Annotations

Annotaions Driven

Product{

XML :
1. Java classes
2. create XMl file
3. configure beans in side xml file
<bean>
........
</bean>
Annoataions:
------------

Beans Configurations, Done by completely Java lang.


All about annaotaions

Spring Provided few annoataions called as

@Configuration
@Bean

What is Spring Bean Configuration class?

A java classs is annoatated with @Configuration annoataion , that class is


called as Spring Beans Configuration calss.

@Configuration :
this aanoataion should be used along with a class.

We have to define a configuration calss.

Two create Bean Object in annoataions we have 2 solutions:

===> Now we have to configure our Bean classes in side Config class.

Spring FW provided an annoataion called as @Bean

@Bean Annoataion is used along with a method inside a configuration


class

Now we have to define a method inside config. classs, which is


responsible for returning resepective bean class Object.

==> Spring Bean Onfiguration is complted in side Config. Class

==> Now Create Spring Conatiner

// Container please refer Spring Bean Config class which is provided as constrct
params
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringBeansConfiguration.class);

// Now Spring Conatiner loads, SpringBeansConfiguration class and find out how many
bean methods
we are Written
// Spring Conatiner will execute all @Bean Methods
// Once @Bean methods are executed by Conatiner, returned Objects will be
maintined as Bean Objects inside //by Spring Conatiner
what will happen , if we use @Bean with same value (iPhone) in second method.

If we are not provided bean Id/name as part of @Bean , then Spring will assign
method name as Bean Name.

Assignment:

Please try to implment Annoataions in side Spring Project.

Req :

Employee{

id
name

Only One Bean Object has to be created with default values of that Object

@Configuration
BeansConfig{

@Bean
Employye getEmp(){

return new Employye();


}

@Component:
----------

This annoatation is uded to create Bean Object of cals.

This Annoataion is used on top of class.

Then we can call that class a Component class.

Now, Spring Container will scans Component classes and Sprinf Conatiner will create
an Object for that Component class

@Component
class Emplpoyye{
}

we should inform to container, where our Component class written, Pakcage name.
many packages :

To Configure Component classes information , Spring Provided 2 ways;

1. an annoation called as @ComponentScan

@ComponentScan:
===============

as part @ComponentScan , we will provide package names where out Component classe
are located

this @ComponentScan annoataion should used along with @Configuration class.


Conatiner will start creating Object for every component class with default value
of properties.

@Component :

In this case, Spring will asiign Calss name Bean Id. camel Case

base package :
--------------

what is base package:?

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

com.icici........

com.naresh.meetins

please make sure base packge name is always, where evr SpringbootApplication class
is avilable.

com.naresh.spring.one
com.naresh.spring.one.twi
com.naresh.spring.one.tow.three
com.naresh.spring.four

How we are creating Bean object ?

1. @Bean Method
2. @Component

Use Cases :
==========

1. How many Objects created for Order?

1 Object Created with Bean Id order.

2. How many Objects can be created for a Java class?

Many

3. If I wan to create another Bean Object for Order class?

Can I achive by using @Component to create more than One Object by Conatiner?

No

we have to use @Bean method :

4. Create only one Bean Object for class called as Product?

@Component

5. Create only one Bean Object for class called as Product


along with some real data of propeties ?

@Bean method for that Bean class

6. Define a class , which object should be created By Default and I want to many
Objects as and when required?
@Component

Can we create more Bean oBjects of a Component class?


Componet + Bean Methods

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

Bean Scopes with Componet class:


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

How many Bean obhjects created ?


1. For Component class, When Conatiner created Object, by default scope id
Singleton

2. Can I change default scope of singleton to prototype for a Component class?


@Scope("prototype") with @Component

total 2 : CourseDetails 1 Employye 1

total 3 : CourseDetails 1 Employye 2 emp1,emp2

NoUniqueBeanDefinitionException: No qualifying bean of type


'com.traning.courses.Employee' available: expected single matching bean but found
2: emp1,emp2

getBean(String) : More than one Bean Object, with Bean ID.

getBean(Class<T>) : only One Bean Object :

Dependecy Injection in Annotations:


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

3 Types of Dependecy Injection

1. Field/Property level Injection


2. Setter Injection
3. Constructor Injection

Field/Property level Injection :


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

To enable field injection , Spring framework provided an annaotaion called as


@Autowired

We have to add annoataion on field level where we are havinf dependency of Objects.

Java Core : Rfelection API

To Achive Field Injection, we are used @Autowired.

@Component
public class College {

@Autowired
private Address address;

}
Address -> College

How many Bean Objects can be created for Address?


many

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating


bean with name 'college': Unsatisfied dependency expressed through field 'address':
No qualifying bean of type 'com.naresh.spring.field.injection.Address' available:
expected single matching bean but found 2: office,home

Address is having Many Objects?

Addrees home = new Address();

@Qualifier:
==========
This Annoataion is used always along with combination of @Autowired

as aprt of @Qualifier , we have to proivde which bean Object has to be Injecyed


when we have more than One bean Object for a class.

@Qualifier : when we have more than One Bean objects of a Dependecy

S1 , S2 : Insatnces

Class : specific bean Objects either s1 or s2?

USe case :
===========

When I have more than One Bean Object of a Dependecy class : Address, I can't
use @Autowired individually.

Using @Qualifier.

Req : eventhough, When I have more than One Bean Object of a Dependecy class
:
@Autowired individually.

and I want ot inject a bean Object by default inside


filed.

@Primary : This Annoataion should be used at Bean Object Declaration level.


"home" object should injeccted by default. No need of @Qulifier

Autowiring with Interfaces and Impl Classes :


===========================================
Assignment :

A Super
B,C : Sub classess

D{
A a;

DI : with Primitives and String :


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

College{

int id;
String name;
itn year;
double fee;

@Value("${<key-name>}")

Library : lombok jar

application.peoperties

application.yaml

Spring Boot :
===========

It will take care of Componet scan and Configuration functionlaities when we are
followinf below rule.

we have to maintain packages falling under base package.

base Package : com.naresh.spring

com.naresh.spring.abc...
com.naresh.spring.xyz...
Configuration and Component Scan

@SpringBootApplication :

= @Configuration + @ComponentScan + @EnableAutoConfiguration

Spring Boot is a wrapper on Spring.

Lombok:
------

This is no where realted Spring.

Lombok is 3rd party java library.

get lombok jar files into our project.

lombok : which will saves time to write seeters , getters , constrcutors,


builder Designe Pattern , toString.

POJO classes :
==============

45 MS :

2000 POJO classes

OrderDetails :

150 properties

5 properties : remove

delete 5 varibales

// find setters and getters of 5 variables : Delete

// ReDefine Constrcutor by deleting 5 variables

// Setters and Getters

1000 lines

1. Class with properties :


// setters
// getteres
// All param condtructors
// toString()

lombok:
2000 POJO classes

Define a small annoataion


@Setter
@Getter
OrderDetails :

150 properties

// Setters and Getters Developer .java -> lombok Process -


> .class

@Value Annoataion :
==================

@Value("${propertyname}")

loads data from application.properties file w.r.to propertyname

Field Injection:

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

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

Constrcutor Injection:

===============================
Injecting Sub/Impl classes as a List of References:
====================================================

List of Values :

[com.naresh.spring.order.example.Elephant@24528a25,
com.naresh.spring.order.example.Lion@17ae98d7,
com.naresh.spring.order.example.Tiger@59221b97]

Tiger : 1 : @Order(1) : 0 index : List High Priority


Elephant : 2 : @Order(2)
Lion : 3 : @Order(3)

[com.naresh.spring.order.example.Tiger@59221b97,
com.naresh.spring.order.example.Elephant@24528a25,
com.naresh.spring.order.example.Lion@17ae98d7]

[com.naresh.spring.order.example.Lion@d71adc2,
com.naresh.spring.order.example.Tiger@3add81c4,
com.naresh.spring.order.example.Elephant@2fb68ec6]

@Order / Ordered Interface:


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

deciding index of Collection Object while injecting all sub/impl classes Object

Interface : Animal

Classes : Tiger, Lion

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

Super 1 -> many Sub Classes


Interface 1 -> Many Impl Classes

A -> X, Y, Z

Collect/ Inject set of all Sub classes as List of References.

I want to create and collect Bean objects for Classes


@Component
ABC

@Component
XYZ
@Component
MNO

Elephant Loading.. Created...


Lion Loading.. Created...
Tiger Loading.. Created...

Tiger : 1 : @Order(1) : High Priority


Elephant : 2 : @Order(2)
Lion : 3 : @Order(3)

@Order(-1)

[com.naresh.spring.order.example.Tiger@17ae98d7,
com.naresh.spring.order.example.Elephant@57dc9128,
com.naresh.spring.order.example.Lion@24528a25]

Assignment : @Order with @Bean Methods :

Assignment : @Order / Ordered with Super and Sub classes

Runners In Spring Boot :


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

Runners : These are Spring Beans which are implemented from Prdefined Spring Boot
Runners

Spring Boot Runner :

Runneres are executed only one time immediatley once run() of Spring Application
is exucted.

The logic has to be executed immediately once Spring Application is started,

1. CommandLineRunner
2. ApplicationRunner

Create a connection pool of data base , Once application is started

Runner Class should marked as @Component

Logic Has to be exuted only one :

Runner Class

// set of logic : 1st

// set of logic : 2nd

// set of logic : 3rd


User @Order :

Spring Boot : scans all runner calsses w.r.to an Order defined by Us .


I am in MyCommandLineRunnerFour method : 3
I am in MyCommandLineRunnerTwo method : 2
I am in MyCommandLineRunnerOne method : 1
After SpringApplication.run method

before Order After Order :

I am in MyCommandLineRunnerOne method
I am in MyCommandLineRunnerTwo method
I am in MyCommandLineRunnerFour method

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

Spring Bean Life Cycle:


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

When we born -> we did -> when we died

init : Creating Bean Object

Configure : DI

// Custom logic

Utilize : Geting bean Object in our logics, Using it every where

//
destroy :

Calculation :

When a specifc Bean OBject is created and then Immediately some logic has to be
executed, we can define Spring Bean life cycle manually

Srping Bean Life Cycle methods in our Code

XML :

attributes

<bean id="universoty" class="" init-method="abc" destroy-method="xyz">.


Java :

Annotaions : we can define our own methods and we will annoatate thos methods
Interface : Pre Defined Abstract methods

destroy : at the time of Application Context getting closed.

Interview Questions

https://github.com/dilipsingh1306/practice-core-java

Assignment

You might also like