0% found this document useful (0 votes)
5 views52 pages

Spring Ecosystem: IoC & DI Explained

Chapter 4 of the document discusses the Spring ecosystem, which provides a programming model for Java-based enterprise applications, focusing on Inversion of Control (IoC) and Dependency Injection (DI) as key concepts. It outlines the structure of the Spring Framework, including its core components, bean management, and various configuration methods such as XML, annotation, and Java-based configurations. Additionally, it covers the lifecycle of beans, auto-wiring features, and the types of dependency injection available.

Uploaded by

Vũ Công Tử
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views52 pages

Spring Ecosystem: IoC & DI Explained

Chapter 4 of the document discusses the Spring ecosystem, which provides a programming model for Java-based enterprise applications, focusing on Inversion of Control (IoC) and Dependency Injection (DI) as key concepts. It outlines the structure of the Spring Framework, including its core components, bean management, and various configuration methods such as XML, annotation, and Java-based configurations. Additionally, it covers the lifecycle of beans, auto-wiring features, and the types of dependency injection available.

Uploaded by

Vũ Công Tử
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 4

SPRING ECOSYSTEM

[Link]
(current: 6.1.12)

1
Chapter 4: Spring EcoSystem

CONTENT

1. Introduction
2. Inversion of Control (IoC)
3. Dependency Injection (DI)
4. Auto-wiring

2
Introduction
• The Spring ecosystem provides a comprehensive programming and
configuration model for modern Java-based enterprise applications - on any
deployment platform.
• A key element of Spring is infrastructural support at the application level: Spring
focuses on the "plumbing" of enterprise applications so that teams can focus on
application-level business logic, without unnecessary ties to specific deployment
environments.

3
Spring Projects
[Link]
Consists of 27 projects

4
Spring History
Rod Johnson Version Date Notes
• “Expert One-on-One 0.9 2003
J2EE Design and
1.0 March 24, 2004 First production release.
Development,” Wrox.
ISBN 0-7645-4385-7, 2.0 2006
2002 3.0 2009
• “Expert One-on-One 4.0 2013
J2EE Development 5.0 2017
without EJB,” Wrox.
ISBN 0-7645-5831-5, 6.0.x November 2022 JDK 17-21, Jakarta EE 9
2024 JDK 17-23, Main
6.1.x November 2023
production line
JDK 17-25, Upcoming
6.2.x November 2024
feature branch 5
Spring Framework Overview
• Although Spring is an ecosystem, the heart of all other projects is based on the
Spring Framework.
• Spring makes it easy to create Java enterprise applications. It provides
everything you need to embrace the Java language in an enterprise environment,
and with the flexibility to create many kinds of architectures depending on an
application’s needs.
• As of Spring Framework 6.0, Spring requires Java 17+.

“Spring”: different things in different contexts


6
Spring Framework Component

7
Spring Framework Core
• Is the core of the Spring ecosystem.
• Based on it, other projects are
developed.
• Foremost amongst these is the Spring
Framework’s Inversion of Control
(IoC) container.

8
Inversion of Control (IoC)
• In software development, Inversion of Control is a basic idea that modifies the
control flow of applications.
• IoC shifts control responsibility from the application to an outside
framework or container through inversion of this control.
• Inversion of Control (IOC) is a design principle used in software architecture to
invert control flow in a system. The IOC design pattern changes the paradigm
of system control. Using the IOC design principle, the management of a system
is inverted so that instead of the client code controlling a program’s flow, the
framework or container contains the program’s flow. IOC allows for more
flexibility and modularity in design and reduces coupling between components,
creating greater flexibility, re-usability, and testability in software systems.

9
Inversion of Control (IoC) (cont.)

10
Dependency Injection (DI)
• Dependency Injection is a software pattern that implements Inversion of
Control to resolve dependencies.
• In DI, objects define their dependencies with other objects. These dependencies
are managed by a container, which is responsible for injecting them and
creating the necessary beans through a process called Inversion of Control
(IoC).

11
Example without DI

Tightly-coupled

12
Example without DI (cont.)

What will happen when the Engine class is changed?

13
Example with DI Inject ICEngine object to Car class

Changes to the Engine class will not


affect to Car class.

14
Example with DI (cont.)
What will happen when we have another engine type? (E.g., Hybrid Engine,
Electricity Engine, ...)

15
Dependency Injection (cont.)
The Dependency Injection pattern involves 3 types of classes.
1. Client Class: The client class (dependent class) is a class which depends on the
service class
2. Service Class: The service class (dependency) is a class that provides service
to the client class.
3. Injector Class: The injector class injects the service class object into the client

16
Dependency Injection (cont.)

17
Type of Dependency Injection
1. Constructor Injection: In the constructor injection, the injector supplies the
service (dependency) through the client class constructor.
2. Property Injection: In the property injection (aka the Setter Injection), the
injector supplies the dependency through a public property of the client class.
3. Method Injection: In this type of injection, the client class implements an
interface which declares the method(s) to supply the dependency and the
injector uses this interface to supply the dependency to the client class.

18
The Spring’s IOC Container
• Remind: IoC is also known as dependency injection (DI) - a process whereby
objects define their dependencies through constructor arguments, arguments to
a factory method, or properties.
• The [Link] and [Link] packages
are the basis for Spring Framework’s IoC container.
• The BeanFactory object provides the configuration framework and basic
functionality, and the ApplicationContext object adds more enterprise-specific
functionality.

19
The Spring’s IOC Container (cont.)
• In Spring, the objects that form the backbone
of your application and that are managed by
the Spring IoC container are called beans.
• A bean is an object that is instantiated,
assembled, and managed by a Spring IoC
container.
• Beans, and the dependencies among them, are
reflected in the configuration metadata used
by a container.

20
The Spring’s IOC Container (cont.)

The primary job of the ApplicationContext is to manage beans.


21
Spring Bean
• In Spring, a bean is an object that the Spring container instantiates, assembles,
and manages.
• Any Java POJO class can be a Spring Bean if configured and initialized through
the container by providing configuration information.
• We should define beans for service layer objects, data access objects (DAOs),
presentation objects, infrastructure objects such as Hibernate SessionFactories,
JMS Queues, and …
• These beans are created with the configuration metadata that you supply to the
container (for example, in the form of XML <bean/> definitions).

22
Spring Bean (cont.)
No Property Description
1 class Mandatory and specifies the bean class to be used to create the bean.
The bean identifier uniquely. In XMLbased configuration metadata, id
2 id/name
and/or name attributes to specify the bean identifier(s).
3 scope The scope of the objects created from a particular bean definition
4 constructor-arg This is used to inject the dependencies
5 properties This is used to inject the dependencies
6 autowiring This is used to inject the dependencies
A lazy-initialized bean tells the IoC container to create a bean instance
7 lazy-initialization
when it is first requested, rather than at the startup.
A callback to be called just after all necessary properties on the bean have
8 initialization
been set by the container.
A callback to be used when the container containing the bean is 23
9 destruction
Spring Bean Scope
• Singleton: (default) Only one instance of the bean will be created per container.
This is the default scope for spring bean.
• Prototype: An instance of the bean will be created for each request.

WEB-CONTEXT
• Request: same as prototype scope, but for web application, an instance of bean
will be created for each HTTP request.
• Session: Each bean instance will be created for each HTTP Session
• Global-Session: Used to create global session beans for Portlet applications.

24
Spring Bean Life Cycle
Container Beans Dependencies Internal Spring Your Custom
started Instantiated Injected Processing Init Method

Bean is Ready for Use


.
.
.
Your Custom Container is Shutdown
Destroy Method (at a certain point)

25
Spring Bean Life Cycle Method
• You can add custom code during bean initialization:

• Calling custom business logic methods

• Setting up handles to resources (databases, files etc)

• You can add custom code during bean destruction:

• Calling custom business logic methods

• Cleanup handles to resources (databases, files etc)

26
Configuring Beans in the Container
• The primary job of the ApplicationContext is to manage beans à application
must provide the bean configuration to the ApplicationContext container.
• Type of configurations:
§ XML-Based Configuration: ClassPathXmlApplicationContext (xml file)
§ Annotation-Based Configuration: AnnotationConfigApplicationContext
§ Java-Based Configuration: GenericWebApplicationContext

Gradle implementation '[Link]:spring-context:6.1.12'


<dependency>
<groupId>[Link]</groupId>
Maven <artifactId>spring-context</artifactId>
<version>6.1.12</version>
</dependency> 27
Configuring Beans in the Container
XML-Based Configuration – Setter Injection
src/main/resources/[Link]

28
Configuring Beans in the Container
XML-Based Configuration – Setter Injection – Object Injection
src/main/resources/[Link]

29
Configuring Beans in the Container
XML-Based Configuration – Setter Injection – Object Injection

30
Configuring Beans in the Container
XML-Based Configuration – Collection Injection

31
Configuring Beans in the Container
XML-Based Configuration – Literal Values Injection

32
Spring’s Auto-wiring
• Auto-wiring feature of spring framework enables you to inject the object
dependency implicitly. It internally uses setter or constructor injection.
• Auto-wiring can't be used to inject primitive and string values. It works with
reference only.
No Mode Description
1 no The default autowiring mode. It means no auto-wiring by default.
2 The byName mode injects the object dependency according to name of the
byName bean. In such case, property name and bean name must be same. It internally
calls setter method.
The byType mode injects the object dependency according to type. So property
3 byType
name and bean name can be different. It internally calls setter method.
The constructor mode injects the dependency by calling the constructor of the
4 constructor
class. It calls the constructor having large number of parameters.
5 autodetect deprecated since Spring 3.
33
Spring’s Auto-wiring (cont.)

explicit

Can be omitted

Find bean with the id = “faculty”

34
Spring’s Auto-wiring (cont.)

Find bean with the type “Faculty”

35
Spring’s Auto-wiring (cont.)

Find bean with the type “Faculty”


but it looks for the class type of the constructor arguments

36
Configuring Beans in the Container
Java-Based Configuration
The central artifacts in Spring’s Java configuration support
are @Configuration-annotated classes and @Bean-annotated methods.
• @Bean annotation:
§ used to indicate that a method instantiates, configures, and initializes a
new object to be managed by the Spring IoC container.
§ For those familiar with Spring’s <beans/> XML configuration,
the @Bean annotation plays the same role as the <bean/> element.
§ Can use @Bean-annotated methods with any Spring @Component.
However, they are most often used with @Configuration beans.
• @Configuration:
§ indicates that its primary purpose is as a source of bean definitions.
§ @Configuration classes let inter-bean dependencies be defined by
37
calling other @Bean methods in the same class.
Configuring Beans in the Container
Java-Based Configuration(cont.)

38
Configuring Beans in the Container
Java-Based Configuration(cont.)

39
Configuring Beans in the Container
Java-Based Configuration(cont.)

40
Configuring Beans in the Container
Java-Based Configuration (cont.)
No Annotation Description
1 @Required This annotation applies to bean property setter methods.
This annotation can apply to bean property setter methods,
non-setter methods, constructor and properties.
2 @Autowired
This annotation allows Spring to resolve and inject
collaborating beans into another bean.
This annotation along with @Autowired can be used to
3 @Qualifier remove the confusion by specifiying which exact bean will be
wired.
JSR-250 Spring supports JSR-250 based annotations which include
4
annotations @Resource, @PostConstruct and @PreDestroy annotations.
JSR 330 Standard [Link]
5 41
Configuring Beans in the Container
Annotation-Based Configuration
• Spring 2.5 introduced annotation-based configuration as the first step to enable
bean configurations in Java.
• In this approach, we first enable annotation-based configuration via XML
configuration. Then we use a set of annotations on our Java classes, methods,
constructors, or fields to configure beans. Some examples of these annotations
are @Component, @Controller, @Service, @Repository, @Autowired,
and @Qualifier.
• Annotation injection is performed before external property injection. Thus,
external configuration (e.g. XML-specified bean properties) effectively overrides
the annotations for properties when wired through mixed approaches.
• Spring provides support for JSR-250 annotations, such
as @PostConstruct and @PreDestroy, as well as support for JSR-330
(Dependency Injection for Java) annotations contained in the
[Link] package such as @Inject and @Named 42
Configuring Beans in the Container
Annotation-Based Configuration (cont.)
Create the XML configuration, [Link] (src/main/resources) to
enable annotations:

You can also use @Configuration


43
annotation with the same purpose
Configuring Beans in the Container
Annotation-Based Configuration (cont.)
<context:annotation-config/> only looks for annotations on beans in the
same application context in which it is defined.
You can also use @Configuration annotation with the same purpose

!"#$%&'()*+&#$
!"#,-#$.$+/0*$12%&+34.3*$$#+*+&#$5*4.678
-(59&0:09*44:;--"#$%&':<
::::
=

44
@Autowired xml config

Field Constructor
Setter

45
@Autowired Java-based config

46
@Autowired Disambiguation

47
@Autowired Disambiguation (cont.)
Error Caused by:
[Link]
[Link]
DefinitionException:
No qualifying bean of
type
'[Link].
disambiguation.

48
Disambiguation solution: @Qualifier

When there are multiple beans of the same type à use @Qualifier to avoid
ambiguity.
Spring uses the bean's name as a default qualifier value.
49
Disambiguation solution: @Primary

@Primary indicates that a particular bean should be given preference when


multiple beans are candidates to be autowired to a single-valued dependency. 50
Inject resources with @Value
!"#$%&'()*+&#$ -(<:&0=0:*55=":&.$+@.*$=?
!"#,-#$.$+/0*$12&(34%&+45.4).5#()0.567 ====!D*:(.160:*55-*+3;<.*$54E,:67
!8)#-.)+9/#()0.160:*55-*+3;*--:&0*+&#$4-)#-.)+&.5 ====-)&F*+.=G.5#()0.=,9G.5#()0.B
67
-(<:&0=0:*55=>--"#$%&'=? ====!D*:(.16H?%##4-.),&55&#$C67
====!@.*$ ====-)&F*+.=/+)&$'=-.),&55&#$B
====-(<:&0=":&.$+@.*$=0:&.$+@.*$17=?
========).+()$=$.A=":&.$+@.*$17B ====-(<:&0=F#&I=I#/#,.+3&$'17=+3)#A5=JKLE0.-+&#$=?
====C ========M&:.=%&:.=N=,9G.5#()0.4'.+M&:.17B
C ========/+)&$'=5=N=$.A=
/+)&$'1M&:.54).*I>::@9+.51%&:.4+#8*+31777B
-(<:&0=0:*55=O*&$=? ========/95+.,4#(+4-)&$+:$157B
====-(<:&0=5+*+&0=F#&I=,*&$1/+)&$'PQ=*)'57=+3)#A5=JKLE0.-+&#$=? ========/95+.,4#(+4-)&$+:$1-.),&55&#$7B
========>$$#+*+&#$"#$%&'>--:&0*+&#$"#$+.E+=0#$+.E+=N ====C
================$.A= C
>$$#+*+&#$"#$%&'>--:&0*+&#$"#$+.E+1>--"#$%&'40:*557B
========":&.$+@.*$=<.*$=N 0#$+.E+4'.+@.*$1":&.$+@.*$40:*557B
========<.*$4I#/#,.+3&$'17B
====C
C 51
Q&A
52

You might also like