13. Spring Core Notes
13. Spring Core Notes
Framework
===========
=> Semi Developed software which provides common logics required for projects
development
=> Frameworks will help the developers to implement more functionality in less time
=> When we use framework to develop the project, we can focus only on business
logic.
==================
Types of Frameworks
==================
Ex: Angular
Ex: Hibernate
=> By using Struts we can develop only Web Layer in the Project ( Controllers )
=> By using Hibernate we can develop only Data Access Layer (Persistence Layer)
Note: To overcome the problems of Struts framework, Spring Framework came into
market.
==============
Spring Modules
==============
1) Spring Core
2) Spring Context
3) Spring JDBC
4) Spring ORM
5) Spring AOP
6) Spring Web MVC
7) Spring Security
8) Spring Social
9) Spring Batch
10) Spring Data JPA
11) Spring REST
12) Spring Cloud
Note: Spring is very flexible framework. It will not force to use all modules.
Based on requirement we can pickup particular module and we can use it.
URL : www.spring.io
===================================================================================
============
2) Dependency Injection
4) Bean Scopes
5) Autowiring etc...
2) Spring Context : It will deal with configurations required for our Spring
Applications.
=> AOP is used to seperate business logics & Secondary logics in the project
Note: If we combine business logics & secondary logics then we will face maintence
issues of our project.
=> In java jdbc we need to write boiler plate code (repeated code) like below
in several classes
5) Spring Web MVC : It is used to develop both Web Applications & Distributed
Applications
Ex:
Note: JDBC will represent data in text format where as Hibernate ORM will represent
data in Objects format.
7) Spring Security
=> Reading data from Excel and store it into database table
=> Monitoring
=> Routing
===================================================================================
============
=============================================================================
Spring Core : It is all about Managing dependencies among the classes with loosely
coupling
=============================================================================
=> In project we will develop several classes. All those classes we can categorize
into 3 types
1) POJO
2) Java Bean
3) Component
================================
What is Pojo ( Plain Old Java Object )
===============================
=> Any Java class which can be compiled by using only JDK software is called as
POJO class.
class Demo1 {
int id;
String name;
}
int id;
String name;
}
// run method
}
===================
What is Java Bean ?
===================
=> Any java class which follows bean specification rules is called as Java Bean.
3) Every private variable should have public setter & public getter method
Note : Bean classes are used to write business logic and to store and retrieve data
===================
What is Component ?
===================
=> The java classes which contains business logic is called as Component classes
=> Controller classes will have logic to deal with Request & Response
Ex: Generate OTP, Send OTP, Send Email, Encrypt & Decrypt PWD
etc...
=> DAO classes will contain the logic to communicate with Database
===================================================================================
============
=> In a project we will develop multiple classes and those classes will be
dependent on other classes.
Ex:
1) Inheritence ( IS - A )
2) Composition ( HAS - A )
=====================
Car & Engine Example
=====================
class Engine {
void start ( ) {
// logic
}
class Car {
void drive( ) {
// star the engine
// drive the car
}
}
=> If we want to drive the car then we need to start the Engine that means Car
class drive ( ) method should call Engine class start ( ) method.
Q) In how many ways Car class can call Engine class method ?
=> in 2 ways
1) Inheritence
2) Composition
package in.ashokit;
if (start >= 1) {
System.out.println("Journey Started");
}
if (start >= 1) {
System.out.println("Journey Started");
}
Note: Tomorrow, if Engine class constructor modified then our Car class will be
effected.
===================================================================================
==============
Note: If we use any approach from above then Car class will become tightley coupled
with Engine class. That is not recommended.
=> Loosely coupling means without creating Object and without Inheriting properties
we should be able to access one class method in another class.
=> If we make any changes in Engine class then Car class shouldn't be effected then
we can say our classes are loosely coupled.
package in.ashokit;
if (start >= 1) {
System.out.println("Journey Started...");
} else {
System.out.println("Engine in trouble...");
}
}
}
---------------------------------------------------------------
package in.ashokit;
---------------------------------------------------------------------------
===========================
What is Dependency Injection ?
============================
=> The process of injecting one class object into another class is called as
'Dependency Injection'.
1) Setter Injection
2) Constructor Injection
3) Field Injection
if (start >= 1) {
System.out.println("Journey Started...");
} else {
System.out.println("Engine in trouble...");
}
}
}
------------------------------------------------------------------------------
=> In the above program 'Car' class is dependent on 'Engine' object that means
'Engine' class object should be injected into 'Car' class.
==============================
Setter Injection (SI)
=============================
=> Setter Injection means, Injecting dependent object into target object using
target class setter method.
car.drive();
}
}
=========================
Constructor Injection ( CI )
========================
=> Constructor Injection means, Injecting dependent object into target object using
target class constructor.
public class Car {
car.drive();
}
}
==============================================================
// Setter Injection - SI
car.setEng(new PetrolEngine());
car.drive();
}
}
===================
Field Injection - FI
===================
=> Field Injection means, injecting depending object into target class using target
class variable is called as Field Injection.
if (start >= 1) {
System.out.println("Journey Started...");
} else {
System.out.println("Engine in trouble...");
}
}
}
###### Note: We can access private variables outside of the class using Reflection
API like below ######
carObj.drive();
}
}
================
IOC Container
================
-> Dependency Injection means creating and injecting dependent bean objects into
target bean classes.
Note : We need to provide " Java classes + Bean Configuration " as input for IOC
then IOC will perform DI and provides Spring Beans which are ready to use.
===================
What is Spring Bean ?
===================
-> Any Java class whose lifecycle (creation to destruction) is managed by IOC is
called as Spring Bean.
1) XML Approach
Note: In Spring we can use both XML & Annotation approaches. SpringBoot will
support only Annotations (no xmls)
=======================
How to Start IoC in Spring ?
=======================
1) BeanFactory (Outdated)
2) ApplicationContext (recommended)
Note: When IoC container started it will read bean defintions from Bean
Configuration File
and it will perform Dependency Injection.
===============================================
First Application Development using Spring Core Module
===============================================
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
</dependencies>
3) Create Required Java classes (Ex: IEngine, PetrolEngine, DieselEngine and Car )
</beans>
5) Create Main class and start IOC Container to test the application.
=================================================
Difference Between BeanFactory & ApplicationContext
=================================================
=> BeanFactory will follow Lazy Loading concept that means when we request then
only it will create Bean object.
=> ApplicationContext will follow Eager Loading for Singleton Beans. For Prototype
beans it will also follow Lazy Loading
-----------------------------------------Note: Spring Bean default scope is
Singleton----------------------------------------------
Eager Loading means creating objects for Spring Bean when IoC starts
Lazy Loading means creating objects for Spring Bean when we call
getBean ( ) method.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
==================================================================
How to differentiate Setter Injection & Construction Injection in Bean Config
File ?
==================================================================
==============================================================
============
Bean Scopes
============
=> Scope represents how many objects should be created for a Spring Bean
2) prototye
3) request
4) session
-> Singleton scope means only one object will be created for the class in IOC
Container. This is default scope of spring bean.
-> Prototype scope means every time new object will be created.
Note: request & session scopes are related to Spring Web MVC Module.
===================================
Why Spring Bean is by default Singleton ?
===================================
=> To save memory of JVM spring team made singleton as default scope for the spring
beans.
Ex: TicketGenerator class is used to generate new Ticket for every customer
===========
Autowiring
===========
1) Manual Wiring
2) Autowiring
-> Manual wiring means programmer will inject dependent object into target object
using
<property/> tag or <constructor-arg/> tag using 'ref' attribute.
-> Autowiring means IoC container will identify dependent bean and it will inject
into target bean
(we no need to use any ref attribute in bean configuration file)
1) byName
2) byType
3) constructor
4) no
Note: Autowiring will not work bydefault, We have to enable autowiring on target
bean like below.
==========
byName
==========
=> byName means IoC will identify dependent bean object based on bean id or bean
name.
</beans>
Note: In the above example Car class variable name is matched with 'DieselENgine'
bean id hence DieselEngine obj will be injected into Car.
========
byType
========
=> byType means IoC will identity dependent bean object based on data type of the
variable in Target class.
</beans>
(or)
</beans>
===========
constructor
===========
package in.ashokit.beans;
if (status >= 1) {
System.out.println("Journey Started..");
} else {
System.out.println("Engine Trouble");
}
}
}
</beans>
===============================================================================
Note: Autowiring is applicable for Reference Type variable (not applicable for
primitive types)
====================
Spring Bean Life Cycle
====================
=> Spring Bean object creation and object destruction will be taken care by IOC
container.
=> We can perform some operations using Bean Life Cycle Methods
2) Progrmmatic approach
3) Annotations
init-method ==> It represents the method which should be called after bean obj
created
destroy-method ==> It represents the method which should be called when bean obj
removing from IoC
package in.ashokit.beans;
public Motor() {
System.out.println("Motor :: Constructor");
}
</beans>
public Motor() {
System.out.println("Motor :: Constructor");
}
public Motor() {
System.out.println("Motor :: Constructor");
}
@PostConstruct
public void m1() throws Exception {
System.out.println("motor started.....");
}
@PreDestroy
public void m2() throws Exception {
System.out.println("motor stopped.....");
}
}
===================================================================================
===
=================================================================================
8) BeanFactory vs ApplicationContext
=================
Spring Annotations
=================