Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

Java Spring Training

Spring – Inversion of Control, Dependency Injection


and Bean definitions
Agenda
Spring Framework
 Spring Setup
 Key features
 Spring Bean
 Dependency Injection
 Relation between DI and IoC
 Spring IoC Containers
 Spring DI

Classification: Restricted Page 2


Spring setup
 Download jars here…
http://repo.spring.io/release/org/springframework/spring/
 Unzip spring-framework-4.x.x.RELEASE-dist.zip
 Jars are available within spring/libs

 Also download jars for Apache Commons Logging


http://commons.apache.org/proper/commons-logging/download_logging.c
gi

 Or use Maven

Classification: Restricted Page 3


Hello World using Spring
 Demo

Classification: Restricted Page 4


Key features of Spring Framework
 Dependency Injection and Inversion of Control

 Aspect Oriented Programming

 Spring Modules

Classification: Restricted Page 5


Bean

Classification: Restricted Page 6


Bean Definition
What is Bean in Java?

It is a reusable component or object that is primarily used in java’s


component based software development.

Classification: Restricted Page 7


Classification: Restricted Page 8
Classification: Restricted Page 9
Classification: Restricted Page 10
Classification: Restricted Page 11
Classification: Restricted Page 12
The Life Cycle of a Message-
Driven Bean
Figure illustrates the stages in the life
cycle of a message-driven bean.
Figure 20-5 Life Cycle of a Message-
Driven Bean
The EJB container usually creates a
pool of message-driven bean
instances. For each instance, the
EJB container performs these tasks:
If the message-driven bean uses
dependency injection, the container
injects these references before
instantiating the instance.
The container calls the method
annotated @PostConstruct, if any.
Like a stateless session bean, a
message-driven bean is never
passivated, and it has only two
states: nonexistent and ready to
receive messages.
Classification: Restricted Page 13
ENTITY BEAN

An "Entity Bean" is a
type of Enterprise
JavaBean, a server-
side Java EE
component, that
represents persistent
data maintained in a
database. An entity
bean can manage its
own persistence or can
delegate this function to
its EJB Container. An
entity bean is identified
Classification: Restricted Page 14
Classification: Restricted Page 15
Dependency Injection
 The technology that actually defines Spring (Heart of Spring).
 Dependency Injection helps us to keep our classes as indepedent as
possible.
 Increase reuse by applying low coupling
 Easy testing
 More understandable

Classification: Restricted Page 16


Dependency Injection
 Dependency injection is a pattern where the container passes objects by
name to other objects, via either constructors, properties, or factory
methods.

 An injection is the passing of a dependency (a service) to a


dependent object (a client). Passing the service to the client, rather than
allowing a client to build or find the service, is the fundamental
requirement of the pattern.

 Two types of Dependency Injection:


 Constructor based
 Setter based

Classification: Restricted Page 17


Relation between DI and IoC
 In software engineering, inversion of control (IoC) describes a design in
which custom-written portions of a computer program receive the flow of
control from a generic, reusable library.

 The Inversion of Control (IoC) is a general concept, and it can be expressed


in many different ways and dependency Injection is merely one concrete
example of Inversion of Control.

Classification: Restricted Page 18


Dependency Injection - IoC Container
 The Spring container (IoC Container) is at the core of the Spring Framework.
 The container will create the objects, wire them together, configure them,
and manage their complete lifecycle from creation till destruction.

19

Classification: Restricted Page 19


Dependency Injection - IoC Container

 The container gets its instructions on


what objects to instantiate, configure,
and assemble by reading configuration
metadata provided.
 The configuration metadata can be
represented either by;
 XML,
 Java annotations,
 Java code.

Classification: Restricted Page 20


Spring IoC Containers…
 Spring BeanFactory Container
 Spring ApplicationContext Container – Recommended for most purposes

Note: The ApplicationContext container includes all functionality of


the BeanFactory container, so it is generally recommended over
the BeanFactory. BeanFactory can still be used for light weight applications
like mobile devices or applet based applications where data volume and
speed is significant.

Classification: Restricted Page 21


Dependency Injection - Code Example

To instantiate the above classes, one way is to do the usual new operator like new
Foo() or new Bar() OR we can use the Spring dependency injection to instantiate these
classes and set the properties accordingly.

22

Classification: Restricted Page 22


Dependency Injection - Code Example

Foo f = new Foo("Cleopatra");

Bar b = new Bar("Arthur",26);


b.setFoo(f);

23

Classification: Restricted Page 23


Dependency Injection - Code Example

Spring's ClassPathXmlApplicationContext is the commonly used object that hold the


information of all the beans that it instantiates.

24

Classification: Restricted Page 24


Dependency Injection - Bean Scopes
Scope Description
Singleton (Default) Scopes a single bean definition to a single object instance per Spring
IoC container.
Prototype Scopes a single bean definition to any number of object instances.

25

Classification: Restricted Page 25


Bean scope - Demo
 Demo of bean scope – Prototype and Singleton

Classification: Restricted Page 26


Other Bean Scopes
Scope Description
singleton This scopes the bean definition to a single instance per Spring
IoC container (default).

prototype This scopes a single bean definition to have any number of


object instances.
request This scopes a bean definition to an HTTP request. Only valid
in the context of a web-aware Spring ApplicationContext.

session This scopes a bean definition to an HTTP session. Only valid


in the context of a web-aware Spring ApplicationContext.

global- This scopes a bean definition to a global HTTP session. Only


session valid in the context of a web-aware Spring
ApplicationContext.

Classification: Restricted Page 27


Bean definition – Configuration metadata
Properties Description
class This attribute is mandatory and specify the bean class to be used to create
the bean.
Name /id This attribute specifies the bean identifier uniquely. In XML-based
configuration metadata, you use the id and/or name attributes to specify
the bean identifier(s).
scope This attribute specifies the scope of the objects created from a particular
bean definition and it will be discussed in bean scopes chapter.

constructor- This is used to inject the dependencies and will be discussed later
arg
properties This is used to inject the dependencies and will be discussed later

autowiring This is used to inject the dependencies and will be discussed later
mode
lazy- A lazy-initialized bean tells the IoC container to create a bean instance
initialization when it is first requested, rather than at startup. Default is false.
mode
initialization A callback to be called just after all necessary properties on the bean have
method been set by the container. It will be discussed in bean life cycle chapter.

destruction A callback to be used when the container containing the bean is


method
Classification: Restricted destroyed. It will be discussed
Pagein
28 bean life cycle chapter.
Spring configuration metadata
 XML based configuration file.
 Annotation-based configuration
 Java-based configuration

Classification: Restricted Page 29


Spring Bean Life-Cycle methods – init and destroy
<bean id="exampleBean"
class="examples.ExampleBean"
init-method=“init”
destroy-method=“destroy” />

public class ExampleBean {


public void init() {
// do some initialization work
}

public void destroy() {


// do some destruction work
}
}

Note: you need to register a shutdown hook registerShutdownHook() method


that is declared on the AbstractApplicationContext class. This will ensures a
graceful shutdown and calls the relevant destroy methods.
Classification: Restricted Page 30
Spring Bean Life-Cycle methods – init and destroy

 Default init and destroy methods for multiple classes can be declared as below, if
the init and destroy method names of all these classes is the same.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-init-method="init"
default-destroy-method="destroy">

<bean id="..." class="...">


<!-- collaborators and configuration for this bean go here -->
</bean>

</beans>

Classification: Restricted Page 31


Bean Definition Inheritance – From another bean
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="helloWorld" class=“demo.HelloWorld">


<property name="message1" value="Hello World!"/>
<property name="message2" value="Hello Second World!"/>
</bean>

<bean id="helloIndia" class=“demo.HelloUS" parent="helloWorld">


<property name="message1" value="Hello US!"/>
<property name="message3" value="Namaste India!"/>
</bean>

</beans>

Classification: Restricted Page 32


Bean Definition Inheritance – Defining Bean Template
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="beanTemplate" abstract="true">


<property name="message1" value="Hello World!"/>
<property name="message2" value="Hello Second World!"/>
<property name="message3" value="Namaste India!"/>
</bean>

<bean id="helloIndia" class=“demo.HelloIndia" parent="beanTemplate">


<property name="message1" value="Hello India!"/>
<property name="message3" value="Namaste India!"/>
</bean>

</beans>

Classification: Restricted Page 33


Constructor based DI
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!-- Definition for textEditor bean -->


<bean id="textEditor" class=“demo.TextEditor">
<constructor-arg ref="spellChecker"/>
</bean>

<!-- Definition for spellChecker bean -->


<bean id="spellChecker" class=“demo.SpellChecker">
</bean>

</beans>

Classification: Restricted Page 34


Setter based DI
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean using inner bean -->
<bean id="textEditor" class=“demo.TextEditor">
<property name="spellChecker">
<bean id="spellChecker" class=“demo.SpellChecker"/>
</property>
</bean>
</beans>

Classification: Restricted Page 35


Exercise:
 Create a Quiz Application
 A Quiz has a list of Questions and associated Answers
 Every Answer associated with a question is a set of answers submitted by
multiple persons
 Inject the list of questions and associated answer set for each question
using DI using beans.xml
 E.g. Question 1: Is Java an OOP language?
Answer 1a: Yes (by Bill)
Answer 1b: Yes, it is (by John)
Answer 1c: No, it is not (by Jack) … no limit on number of answers
Note: Every set of answers is actually a list of answer objects. Each answer
object has an id, answerString, submittedBy. So we need to understand how
this collection can be injected in Beans.xml

Classification: Restricted Page 36


Topics to be covered in next session
 Auto-wiring
 Annotations based configuration
 Java based configuration

Classification: Restricted Page 37


Thank you!

Classification: Restricted Page 38

You might also like