KEMBAR78
Spring - Part 1 - IoC, Di and Beans | PPSX
Java Spring Training
Spring – Inversion of Control, Dependency Injection
and Bean definitions
Page 1Classification: Restricted
Agenda
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
Page 2Classification: Restricted
Spring Framework
• Spring is the most popular application development framework for
enterprise Java.
• Open source Java platform since 2003.
• Spring supports all major application servers and JEE standards.
• Spring handles the infrastructure so you can focus on your application
• https://spring.io/
Page 3Classification: Restricted
Spring history
Page 4Classification: Restricted
Spring Framework
Page 5Classification: Restricted
Core Container
• The Core module provides the fundamental parts of the framework,
including the IoC and Dependency Injection features.
• The Bean module provides BeanFactory which is a sophisticated
implementation of the factory pattern.
• The Context module builds on the solid base provided by the Core and
Beans modules and it is a medium to access any objects defined and
configured. The ApplicationContext interface is the focal point of the
Context module.
• The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Page 6Classification: Restricted
Data Access / Integration
• The JDBC module provides a JDBC-abstraction layer that removes the need
to do tedious JDBC related coding.
• The ORM module provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML
mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• The Java Messaging Service JMS module contains features for producing
and consuming messages.
• The Transaction module supports programmatic and declarative
transaction management for classes that implement special interfaces and
for all your POJOs.
Page 7Classification: Restricted
Web Layer
• The Web module provides basic web-oriented integration features such as
multipart file-upload functionality and the initialization of the IoC container
using servlet listeners and a web-oriented application context.
• The Web-MVC module contains Spring's model-view-controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-way
communication between client and server in web applications.
• The Web-Portlet module provides the MVC implementation to be used in a
portlet environment and mirrors the functionality of Web-Servlet module.
Page 8Classification: Restricted
Miscellaneous
• The AOP module provides aspect-oriented programming implementation
allowing you to define method-interceptors and pointcuts to cleanly
decouple code that implements functionality that should be separated.
• The Aspects module provides integration with AspectJ which is again a
powerful and mature aspect oriented programming (AOP) framework.
• The Instrumentation module provides class instrumentation support and
class loader implementations to be used in certain application servers.
• The Messaging module provides support for STOMP as the WebSocket sub-
protocol to use in applications. It also supports an annotation programming
model for routing and processing STOMP messages from WebSocket
clients.
• The Test module supports the testing of Spring components with JUnit or
TestNG frameworks.
Page 9Classification: Restricted
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.cgi
• Or use Maven
Page 10Classification: Restricted
Hello World using Spring
• Demo
Page 11Classification: Restricted
Key features of Spring Framework
• Dependency Injection and Inversion of Control
• Aspect Oriented Programming
• Spring Modules
Page 12Classification: Restricted
Bean
Page 13Classification: Restricted
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
Page 14Classification: Restricted
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
Page 15Classification: Restricted
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.
Page 16Classification: Restricted
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.
16
Page 17Classification: Restricted
• 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.
Dependency Injection - IoC Container
Page 18Classification: Restricted
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.
Page 19Classification: Restricted
Dependency Injection - Code Example
19
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.
Page 20Classification: Restricted
Dependency Injection - Code Example
20
Foo f = new
Foo("Cleopatra");
Bar b = new
Bar("Arthur",26);
b.setFoo(f);
Page 21Classification: Restricted
Dependency Injection - Code Example
21
Spring's ClassPathXmlApplicationContext is the commonly used object that
hold the information of all the beans that it instantiates.
Page 22Classification: Restricted
Dependency Injection - Bean Scopes
22
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.
Page 23Classification: Restricted
Bean scope - Demo
• Demo of bean scope – Prototype and Singleton
Page 24Classification: Restricted
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-
session
This scopes a bean definition to a global HTTP session. Only
valid in the context of a web-aware Spring
ApplicationContext.
Page 25Classification: Restricted
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-
arg
This is used to inject the dependencies and will be discussed later
properties This is used to inject the dependencies and will be discussed later
autowiring
mode
This is used to inject the dependencies and will be discussed later
lazy-
initialization
mode
A lazy-initialized bean tells the IoC container to create a bean instance
when it is first requested, rather than at startup. Default is false.
initialization
method
A callback to be called just after all necessary properties on the bean have
been set by the container. It will be discussed in bean life cycle chapter.
destruction
method
A callback to be used when the container containing the bean is destroyed.
It will be discussed in bean life cycle chapter.
Page 26Classification: Restricted
Spring configuration metadata
• XML based configuration file.
• Annotation-based configuration
• Java-based configuration
Page 27Classification: Restricted
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.
Page 28Classification: Restricted
Spring Bean Life-Cycle methods – init and destroy
Page 29Classification: Restricted
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>
Page 30Classification: Restricted
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>
Page 31Classification: Restricted
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>
Page 32Classification: Restricted
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>
Page 33Classification: Restricted
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
Page 34Classification: Restricted
Topics to be covered in next session
• Auto-wiring
• Annotations based configuration
• Java based configuration
Page 35Classification: Restricted
Thank you!

Spring - Part 1 - IoC, Di and Beans

  • 1.
    Java Spring Training Spring– Inversion of Control, Dependency Injection and Bean definitions
  • 2.
    Page 1Classification: Restricted Agenda SpringFramework • Core Container • Data Access/Integration • Web Layer • Spring Setup • Key features • Spring Bean • Dependency Injection • Relation between DI and IoC • Spring IoC Containers • Spring DI
  • 3.
    Page 2Classification: Restricted SpringFramework • Spring is the most popular application development framework for enterprise Java. • Open source Java platform since 2003. • Spring supports all major application servers and JEE standards. • Spring handles the infrastructure so you can focus on your application • https://spring.io/
  • 4.
  • 5.
  • 6.
    Page 5Classification: Restricted CoreContainer • The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features. • The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern. • The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module. • The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime.
  • 7.
    Page 6Classification: Restricted DataAccess / Integration • The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding. • The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. • The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. • The Java Messaging Service JMS module contains features for producing and consuming messages. • The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs.
  • 8.
    Page 7Classification: Restricted WebLayer • The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context. • The Web-MVC module contains Spring's model-view-controller (MVC) implementation for web applications. • The Web-Socket module provides support for WebSocket-based, two-way communication between client and server in web applications. • The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.
  • 9.
    Page 8Classification: Restricted Miscellaneous •The AOP module provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. • The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented programming (AOP) framework. • The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers. • The Messaging module provides support for STOMP as the WebSocket sub- protocol to use in applications. It also supports an annotation programming model for routing and processing STOMP messages from WebSocket clients. • The Test module supports the testing of Spring components with JUnit or TestNG frameworks.
  • 10.
    Page 9Classification: Restricted Springsetup • 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.cgi • Or use Maven
  • 11.
    Page 10Classification: Restricted HelloWorld using Spring • Demo
  • 12.
    Page 11Classification: Restricted Keyfeatures of Spring Framework • Dependency Injection and Inversion of Control • Aspect Oriented Programming • Spring Modules
  • 13.
  • 14.
    Page 13Classification: Restricted DependencyInjection • 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
  • 15.
    Page 14Classification: Restricted DependencyInjection • 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
  • 16.
    Page 15Classification: Restricted Relationbetween 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.
  • 17.
    Page 16Classification: Restricted DependencyInjection - 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. 16
  • 18.
    Page 17Classification: Restricted •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. Dependency Injection - IoC Container
  • 19.
    Page 18Classification: Restricted SpringIoC 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.
  • 20.
    Page 19Classification: Restricted DependencyInjection - Code Example 19 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.
  • 21.
    Page 20Classification: Restricted DependencyInjection - Code Example 20 Foo f = new Foo("Cleopatra"); Bar b = new Bar("Arthur",26); b.setFoo(f);
  • 22.
    Page 21Classification: Restricted DependencyInjection - Code Example 21 Spring's ClassPathXmlApplicationContext is the commonly used object that hold the information of all the beans that it instantiates.
  • 23.
    Page 22Classification: Restricted DependencyInjection - Bean Scopes 22 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.
  • 24.
    Page 23Classification: Restricted Beanscope - Demo • Demo of bean scope – Prototype and Singleton
  • 25.
    Page 24Classification: Restricted OtherBean 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- session This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
  • 26.
    Page 25Classification: Restricted Beandefinition – 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- arg This is used to inject the dependencies and will be discussed later properties This is used to inject the dependencies and will be discussed later autowiring mode This is used to inject the dependencies and will be discussed later lazy- initialization mode A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup. Default is false. initialization method A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter. destruction method A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter.
  • 27.
    Page 26Classification: Restricted Springconfiguration metadata • XML based configuration file. • Annotation-based configuration • Java-based configuration
  • 28.
    Page 27Classification: Restricted SpringBean 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.
  • 29.
    Page 28Classification: Restricted SpringBean Life-Cycle methods – init and destroy
  • 30.
    Page 29Classification: Restricted BeanDefinition 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>
  • 31.
    Page 30Classification: Restricted BeanDefinition 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>
  • 32.
    Page 31Classification: Restricted Constructorbased 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>
  • 33.
    Page 32Classification: Restricted Setterbased 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>
  • 34.
    Page 33Classification: Restricted 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
  • 35.
    Page 34Classification: Restricted Topicsto be covered in next session • Auto-wiring • Annotations based configuration • Java based configuration
  • 36.