0% found this document useful (0 votes)
12 views37 pages

Spring Framework: Dependency Injection Guide

The document provides an overview of the Spring Framework, including key concepts such as Dependency Injection, Inversion of Control, and various types of Spring Beans. It discusses the importance of loose coupling in software design and outlines the goals of building applications using Spring. Additionally, it covers Spring's dependency management, bean scopes, and important annotations for configuring and managing components within the framework.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views37 pages

Spring Framework: Dependency Injection Guide

The document provides an overview of the Spring Framework, including key concepts such as Dependency Injection, Inversion of Control, and various types of Spring Beans. It discusses the importance of loose coupling in software design and outlines the goals of building applications using Spring. Additionally, it covers Spring's dependency management, bean scopes, and important annotations for configuring and managing components within the framework.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

SPRING Mentor : Rahul Dixit

FRAMEWORK
TERMINOLOGY
Terminology:-Dependency Injection, IOC, Auto wiring, Auto
configuration, Starter Projects.
Application :- Web app, REST API, Full Stack
Variety of other framework, tool and platform integrations: Maven,
Spring Data, JPA, Hibernate, Docker and Cloud
GETTING STARTED WITH
SPRING FRAMEWORK - WHY?
You can build a variety of applications using Java,
Spring and Spring Boot:
 Web
 REST API
 Full Stack
 Microservices
Irrespective of the app you are building:
 Spring framework provides all the core features
 Understanding Spring helps you learn Spring Boot easily
 Helps in debugging problems quickly
WHY IS COUPLING IMPORTANT?
Coupling: How much work is involved in changing
something?
 Coupling is important everywhere:
 An engine is tightly coupled to a Car
 A wheel is loosely coupled to a Car
 You can take a laptop anywhere you go A computer, on the other hand, is a little bit more
difficult to move
 Coupling is even more important in building great software
Only thing constant in technology is change
 Business requirements change
 Frameworks change
 Code changes
 We want Loose Coupling as much as possible
 We want to make functional changes with as less code changes as
possible
Let's explore how Java Interfaces and Spring
Framework help with Loose Coupling!
GETTING STARTED WITH
SPRING FRAMEWORK
Design DrawingApp to draw (Circle, Rectangle,
Square etc) in an iterative approach:

Iteration 1: Tightly Coupled Java Code Iteration 3: Loose Coupling -


 Drawing class Spring Level 1
 Draw method
 Spring Beans
 Game classes: Circle, Rectangle, Square
 Spring framework will manage objects and
etc wiring
Iteration 2: Loose Coupling -
Interfaces
Iteration 4: Loose Coupling -
 Drawing class Shape interface Spring Level 2
 Shape classes: Circle, Rectangle, Square  Spring Annotations
etc  Spring framework will create, manage &
auto-wire objects
GETTING STARTED WITH
SPRING FRAMEWORK -
GOALS
Goal: Understand core features of Spring Framework
Approach: Build a Loose Coupled Hello World Drawing App with Modern Spring
Approach
 Get Hands-on with Spring and understand:
 Why Spring?
 Terminology
 Tight Coupling and Loose Coupling
 IOC Container
 Application Context
 Component Scan
 Dependency Injection
 Spring Beans
 Auto Wiring
SPRING QUESTIONS YOU
MIGHT BE THINKING ABOUT
Question 1: Spring Container vs Spring Context vs IOC Container vs
Application Context
Question 2: Java Bean vs Spring Bean
Question 3: How can I list all beans managed by Spring Framework?
Question 4: What if multiple matching beans are available?
Question 5: Spring is managing objects and performing auto-wiring.
 BUT aren't we writing the code to create objects?
 How do we get Spring to create objects for us?

Question 6: Is Spring really making things easy?


WHAT IS SPRING
CONTAINER?
Spring Container: Manages Spring beans & their lifecycle
1: Bean Factory: Basic Spring Container
2: Application Context: Advanced Spring Container with
enterprise-specific features
 Easy to use in web applications
 Easy internationalization
 Easy integration with Spring AOP
Which one to use?: Most enterprise applications use
Application Context
 Recommended for web applications, web services - REST API and
microservices
EXPLORING SPRING
DEPENDENCY INJECTION
Constructor Injection : - Dependencies are set by Creating
the bean using its constructor
Setter Injection :- Dependencies are set by calling setter
methods on your beans
Field :- No setter or constructor .Dependency Injected using
reflection.
Q Which is better to inject Dependencies
 Spring Team Recommends Constructor based Injection. Because all
Initialization Done By Only One Method i.e. Constructor
FIELD INJECTION
@Component
class BussinesLogic{
@Autowired @Component
Dependency1 dependency1;
class Dependency1{}
@Autowired
Dependency2 dependency2; @Component
@Override
class Dependency2{}
public String toString() {
return "BussinesLogic [dependency1="
+ dependency1 + ", dependency2=" +
dependency2 + "]";
}
SETTER INJECTION
@Autowired
public void setDependency2(Dependency2
@Component dependency2) {
class BussinesLogic{ [Link]("Setter of
Dependency 2");
Dependency1 dependency1;
this.dependency2 = dependency2;
Dependency2 dependency2; }
@Autowired @Override
public String toString() {
public void
setDependency1(Dependency1 return "BussinesLogic [dependency1=" +
dependency1) { dependency1 + ", dependency2=" +
dependency2 + "]";
[Link]("Setter of }
Dependency 1");
}
this.dependency1 = dependency1;
}
CONSTRUCTOR INJECTION
EXECUTED WITH @AUTOWIRED MANAGED BY SPRING
:-
@Component
@Override
class BussinesLogic{
Dependency1 dependency1;
public String toString()
Dependency2 dependency2;
{
@Autowired return "BussinesLogic
public BussinesLogic(Dependency1 [dependency1=" +
dependency1, Dependency2 dependency2) {
dependency1 + ",
[Link]("Constructor
Injection");
dependency2=" +
this.dependency1 = dependency1;
dependency2 + "]";
this.dependency2 = dependency2; }
}
}
EXPLORING AUTO-WIRING IN
DEPTH
When a dependency needs to be @Autowired, IOC container looks
for matches/candidates (by name and/or type)
1. If no match is found Result: Exception is thrown
2. One match is found Result: Autowiring is successful
3. Multiple candidates Result: Exception is thrown
4. You need to help Spring Framework choose between the
candidates
@Primary & @Qualifier Comes Into a Picture
@PRIMARY VS @QUALIFIER -
WHICH ONE TO USE?
@Primary - A bean should be given
preference when multiple candidates are
qualified
@Qualifier - A specific bean should be auto-
wired (name of the bean can be used as
qualifier)
1. Just @Autowired: Give me (preferred Bean)
2. @Autowired + @Qualifier
 @Qualifier has higher priority then @Primary
INVERSION OF CONTROL
In Our Initial Program We Explicitly create an Object and Inject It
Explicitly. But Here everything is managed by Spring Called IoC
(Inversion Of Control)
SPRING FRAMEWORK -
IMPORTANT TERMINOLOGY
@Component (..): An instance of class will be managed by Spring
framework
Dependency: Drawing needs
 Shape impl! Shape Impl (Ex: Circle) is a dependency of Drawing

Component Scan: How does Spring Framework find component classes?


 It scans packages! (@ComponentScan(“packageName"))

Dependency Injection: Identify beans, their dependencies and wire


them together (provides IOC - Inversion of Control)
 Spring Beans: An object managed by Spring Framework
 IoC container: Manages the lifecycle of beans and dependencies Types:
ApplicationContext (complex), BeanFactory (simpler features - rarely used)
 Autowiring: Process of wiring in dependencies for a Spring Bean
WHY DO WE HAVE A LOT OF
DEPENDENCIES?
In Drawing Hello World App, With Spring Framework:
we have very few classes  INSTEAD of FOCUSING on objects,
their dependencies and wiring
BUT RealWorld applications  You can focus on the business logic of your
are much more complex: application!
 Multiple Layers (Web, Business,  Spring Framework manages the
Data etc) lifecycle of objects:
 Each layer is dependent on the  Mark components using annotations:
layer below it! @Component (and others..)
 Mark dependencies using @Autowired
 Example: Business Layer class talks to a
data layer class  Allow Spring Framework to do its magic!
 Data Layer class is a dependency of
Business Layer class Ex:
 There are thousands of such dependencies BusinessCalculationService
in every application!
E.G.
@Configuration public interface DataService {
@ComponentScan public int [] retrieveData();
public class
RealWorldExampleContextLauncher { }
public static void main(String[] args) ===================
{
====
try(var context = new
AnnotationConfigApplicationContext(Real
[Link]))
{
[Link]([Link]
Names()).forEach([Link]::println);
[Link]([Link](Buss
[Link]).findMax());
@Component
public class BussinessService {
private DataService dataService;

@Autowired
public BussinessService(DataService dataService) {
super();
[Link] = dataService;
}

public int findMax() {


return
[Link]([Link]()).max().orElse(0)
;}}
@Component @Component
public class @Primary
MongoDbDataService public class MySqlDataService
implements DataService { implements DataService {
public int[] retrieveData() public int[] retrieveData() {
{
return new int []
return new int [] {11,22,33,44,55,66,77,88,99};
{1,2,3,4,5,6,7,8,9};
}
}

}
}
EXPLORING LAZY INITIALIZATION
OF SPRING BEANS
Default initialization for Spring Beans:
Eager initialization is recommended:
 Errors in the configuration are discovered immediately at
application startup
However, you can configure beans to be lazily initialized
using Lazy annotation:
 NOT recommended (AND) Not frequently used

Lazy annotation:
 Can be used almost everywhere @Component and @Bean are
used
 Lazy-resolution proxy will be injected instead of actual
dependency
COMPARING LAZY
INITIALIZATION VS EAGER
INITIALIZATION
Heading Lazy Initialization
Bean initialized when it
Eager Initialization
Initialization Bean initialized at startup of the
is first made use of in
time application
the application
Default NOT Default Default
@Lazy OR @Lazy(value=false) OR (Absence of
Code Snippet
@Lazy(value=true) @Lazy)
What happens
if there are Errors will result in Errors will prevent application from
errors in runtime exceptions starting up
initializing?
Usage Rarely used Very frequently used
Memory Less (until bean is
All beans are initialized at startup
Consumption initialized)
Recommended Beans very rarely used
Most of your beans
Scenario in your app
E.G. @LAZY
@Configuration @Component
@ComponentScan class A{}
public class LazyInitializationExample {
@Component
@Lazy
public static void main(String[] args) {
class B{

try(var context = new A a;


AnnotationConfigApplicationContext(LazyInitial
[Link])) B(A a)
{ {
[Link]([Link]() [Link]("Dependency
).forEach([Link]::println);
Injected");
[Link]("All set for Lazy
Initialization"); this.a=a;}
[Link]([Link]);}}} }
SPRING BEAN SCOPES
Spring Beans are defined to be used in a specific scope:
 Singleton - One object instance per Spring IoC container
 Prototype - Possibly many object instances per Spring IoC
container
 Scopes applicable ONLY for web-aware Spring
ApplicationContext
 Request - One object instance per single HTTP request
 Session - One object instance per user HTTP Session
 Application - One object instance per web application runtime
 Websocket - One object instance per WebSocket instance

Java Singleton vs Spring Singleton


 Spring Singleton: One object instance per Spring IoC container
 Java Singleton : One object instance per JVM
E.G.
@Component try(var context = new
AnnotationConfigApplicationContext(Sim
class NormalClass{} [Link])){
@Component [Link]([Link](Nor
@Scope(value = [Link]));
ConfigurableBeanFactory.SCOPE_PROTOTYP [Link]([Link](Nor
E) [Link]));
class PrototypeClass{} [Link]([Link](Nor
@Configuration [Link]));

@ComponentScan [Link]([Link](Pro
[Link]));
public class
SimpleSpringContextLauncher { [Link]([Link](Pro
[Link]));
public static void main(String[] args)
{ [Link]([Link](Pro
[Link]));
[Link]([Link](Pro
PROTOTYPE VS SINGLETON
BEAN
HeadingSCOPE
Prototype Singleton
Possibly Many per Spring IOC
Instances Container One per Spring IOC Container

New bean instance created


every time the bean is
Beans referred to Same bean instance reused
Default NOT Default Default

@Scope(value= @Scope(value=
[Link] [Link]
Code Snippet OPE_PROTOTYPE) PE_SINGLETON OR Default
Usage Rarely used Very frequently used
Recommended
@POSTCONSTRUCT &
@PREDESTROY
@Component [Link]();}
class SomeClass{ @PreDestroy
SomeDependency someDependency; void cleanUp() {
[Link]("CleanUp Activity is
Done");
public SomeClass(SomeDependency
someDependency) { }}
super(); @Component
[Link] = someDependency; class SomeDependency{
[Link]("All Dependencies public void getReady() {
are Ready");
[Link]("All Initialization
} is done");
@PostConstruct }}
void initialize(){
JAKARTA CONTEXTS &
DEPENDENCY INJECTION (CDI)
Spring Framework V1 was released in 2004
CDI specification introduced into Java EE 6 platform in December 2009
Now called Jakarta Contexts and Dependency Injection (CDI)
CDI is a specification (interface)
 Spring Framework implements CDI • To Add Jakarta Annotation:-
• Add Libraries By Simply Adding Dependencies in
[Link]
Important Inject API Annotations:
 Inject (~Autowired in Spring) <!--
[Link]
 Named (~Component in Spring) ct/[Link]-api -->
 Qualifier <dependency>
 Scope <groupId>[Link]</groupId>
 Singleton <artifactId>[Link]-api</artifactId>
<version>2.0.1</version>
</dependency>
SPRING STEREOTYPE
ANNOTATIONS -
@COMPONENT & MORE..
@Component - Generic annotation applicable for any class
Base for all Spring Stereotype Annotations
Specializations of @Component:
 @Service - Indicates that an annotated class has business logic
 @Controller - Indicates that an annotated class is a "Controller" (e.g. a web controller) Used to
define controllers in your web applications and REST API
 @Repository - Indicates that an annotated class is used to retrieve and/or manipulate data in a
database

What should you use?


Use the most specific annotation possible
Why?
 By using a specific annotation, you are giving more information to the framework about your
intentions.
 You can use AOP at a later point to add additional behavior
QUICK REVIEW OF IMPORTANT
SPRING ANNOTATIONS
@Configuration:- Indicates that a class declares one or more @Bean methods and may
be processed by the Spring container to generate bean definitions
@ComponentScan :- Define specific packages to scan for components. If specific
packages are not defined, scanning will occur from the package of the class that declares
this annotation
@Bean:- Indicates that a method produces a bean to be managed by the Spring
container.
@Component:- Indicates that an annotated class is a "component“
@Service:- Specialization of @Component indicating that an annotated class has
business logic
@Controller:- Specialization of @Component indicating that an annotated class is a
"Controller" (e.g. a web controller). Used to define controllers in your web applications and
REST API @Repository Specialization of
@Repository:- indicating that an annotated class is used to retrieve and/or manipulate
data in a database.
@Primary :- Indicates that a bean should be given preference when multiple candidates
@Qualifier:- Used on a field or parameter as a qualifier for candidate beans
when autowiring.
@Lazy :- Indicates that a bean has to be lazily initialized. Absence of @Lazy
annotation will lead to eager initialization.
@Scope :- (value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) Defines a
bean to be a prototype - a new instance will be created every time you refer to
the bean. Default scope is singleton - one instance per IOC container.
@PostConstruct :- Identifies the method that will be executed after
dependency injection is done to perform any initialization.
@PreDestroy :- Identifies the method that will receive the callback
notification to signal that the instance is in the process of being removed by
the container. Typically used to release resources that it has been holding.
@Named :- Jakarta Contexts & Dependency Injection (CDI) Annotation similar
to Component.
@Inject :- Jakarta Contexts & Dependency Injection (CDI) Annotation similar
to Autowired
QUICK REVIEW OF IMPORTANT
SPRING CONCEPTS
Dependency Injection :- Identify beans, their dependencies and wire them
together (provides IOC - Inversion of Control).
Constr. injection :- Dependencies are set by creating the Bean using its
Constructor.
Setter injection :- Dependencies are set by calling setter methods on your beans.
Field injection :- No setter or constructor. Dependency is injected using reflection.
IOC Container :- Spring IOC Context that manages Spring beans & their lifecycle.
Bean Factory :- Basic Spring IOC Container.
Application Context :- Advanced Spring IOC Container with enterprise-specific
features - Easy to use in web applications with internationalization features and
good integration with Spring AOP.
Spring Beans :- Objects managed by Spring
FRAMEWORK, MODULES
AND PROJECTS
Spring Core : IOC Container, Dependency Injection, Auto
Wiring, ..
 These are the fundamental building blocks to:
 Building web applications
 Creating REST API
 Implementing authentication and authorization
 Talking to a database
 Integrating with other systems
 Writing great unit tests

Let's now get a Spring:


 Spring Framework
 Spring Modules
 Spring Projects
FRAMEWORK AND
MODULES
Spring Framework contains multiple Spring
Modules:
 Fundamental Features: Core (IOC Container, Dependency
Injection, Auto Wiring, ..)
 Web: Spring MVC etc (Web applications, REST API)
 Web Reactive: Spring WebFlux etc
 Data Access: JDBC, JPA etc
 Integration: JMS (Java Message Services) etc
 Testing: Mock Objects, Spring MVC Test etc

Why is Spring Framework divided into Modules?


 Each application can choose modules they want to make use of

SPRING PROJECTS
Application architectures evolve continuously
 Web > REST API > Microservices > Cloud > ...

Spring evolves through Spring Projects:


 First Project: Spring Framework
 Spring Security: Secure your web application or REST API or microservice
 Spring Data: Integrate the same way with different types of databases : NoSQL
and Relational
 Spring Integration: Address challenges with integration with other applications
 Spring Boot: Popular framework to build microservices
 Spring Cloud: Build cloud native applications
FRAMEWORK, MODULES
AND PROJECTS
Hierarchy: Spring Projects > Spring Framework > Spring Modules
Why is Spring Eco system popular?
 Loose Coupling: Spring manages creation and wiring of beans and
dependencies
 Makes it easy to build loosely coupled applications
 Make writing unit tests easy! (Spring Unit Testing)
 Reduced Boilerplate Code: Focus on Business Logic Example: No need for
exception handling in each method! All Checked Exceptions are converted to
Runtime or Unchecked Exceptions
 Architectural Flexibility: Spring Modules and Projects You can pick and choose
which ones to use (You DON'T need to use all of them!)
 Evolution with Time: Microservices and Cloud Spring Boot, Spring Cloud etc!
THANKS

You might also like