SlideShare una empresa de Scribd logo
1 de 164
Introduction to Spring
Oded Nissan
Introduction to Spring
•
•
•
•
•
•

Introduction
About the Lecturer
Topics
Exercises
Agenda
Questions ?

Copyright(c) Oded Nissan 2010
Introduction to Spring
•
•
•
•
•
•

Introduction
About the Lecturer
Topics
Exercises
Agenda
Questions ?

Copyright(c) Oded Nissan 2010
Agenda
•
•
•
•
•

Spring architecture and overview
Dependency Injection and the IOC Container
Resources
Spring AOP
Summary

Copyright(c) Oded Nissan 2010
Spring architecture and overview
• Spring Introduction
• Spring Architecture
• The Spring Framework Components

Copyright(c) Oded Nissan 2010
Dependency Injection and the IOC
Container
•
•
•
•
•

What is dependency injection?
IOC container overview
Working with Spring beans
Managing dependencies
Advanced features

Copyright(c) Oded Nissan 2010
Resources
•
•
•
•
•

Available Resource implementations
The Resource Loader
Injecting Resources
ApplicationContext and Resources
Resources and Wildcards

Copyright(c) Oded Nissan 2010
Spring AOP
•
•
•
•
•

What is AOP ?
AOP Concepts
Spring AOP options
Example
Summary

Copyright(c) Oded Nissan 2010
Spring architecture and overview

Copyright(c) Oded Nissan 2010
Spring architecture and overview
• Spring Introduction
• Spring Architecture
• The Spring Framework Components

Copyright(c) Oded Nissan 2010
Resources
• http://www.springsource.org - the home of the
Spring Framework.
• http://www.springhub.com – a hub for Spring
resources.
• http://static.springsource.org/spring/docs/curren
t/spring-framework-reference/html/ - the Spring
Framework reference documentation.
• http://static.springsource.org/spring/docs/3.0.x/j
avadoc-api/ - Spring API docs.
• http://opensource.atlassian.com/confluence/spri
ng/dashboard.action - Spring community wiki.
Copyright(c) Oded Nissan 2010
Spring Introduction
• What Is Spring ?
– The Spring Framework is an open source
application framework that aims to make JEE
development easier.
– Popular open source framework
– Based on the dependency injection pattern
– Developed by Rod Johnson in 2004
– Current version is 3.0

Copyright(c) Oded Nissan 2010
Why do we need Spring ?
•
•
•
•

JEE is too complex and too tightly coupled.
An alternative to the complex EJB technology.
JEE is based on tools and code generators.
Lightweight framework that does not need a
full JEE server to run.
• Better performance.
• JEE is hard to unit test.

Copyright(c) Oded Nissan 2010
Spring Principles
• Spring is a non-invasive framework.
• Spring provides a consistent programming
model, usable in any environment
• Spring aims to promote code reuse.
• Spring aims to facilitate Object Oriented
design in JEE applications
• Spring aims to facilitate good programming
practice, such as programming to interfaces,
rather than classes
Copyright(c) Oded Nissan 2010
Spring Principles
• Spring promotes plugability
• Spring facilitates the extraction of configuration
values from Java code into XML or properties
files.
• Spring is designed so that applications using it are
as easy as possible to test
• Spring is consistent
• Spring promotes architectural choice
• Spring does not reinvent the wheel
Copyright(c) Oded Nissan 2010
Spring Architecture
•
•
•
•

Spring is designed as a modular framework.
Modules as separate and not tightly coupled.
Compatible with all application servers.
Easy integration into JEE or stand alone Java
applications.

Copyright(c) Oded Nissan 2010
Spring Architecture

Copyright(c) Oded Nissan 2010
Spring Usage Scenarios
• One of the advantages of spring is that it’s not
a “take it or leave it” framework.
• Not all spring modules need to be used.
• Spring modules can be easily integrated with
other frameworks.
• Spring also provides simplified APIs to JEE
services.

Copyright(c) Oded Nissan 2010
Full Spring Web application

Copyright(c) Oded Nissan 2010
Spring as a Middle Tier

Copyright(c) Oded Nissan 2010
Spring as a Remoting Framework

Copyright(c) Oded Nissan 2010
Spring Framework Components
•
•
•
•
•
•

IOC Container.
Aspect Oriented Programming Framework.
Data access abstraction.
Transaction management.
MVC web framework.
Integration

Copyright(c) Oded Nissan 2010
The IOC Container
• The technology that Spring is most identified
with is Inversion of Control, and specifically
the Dependency Injection flavor of Inversion of
Control.
• Inversion of Control is best understood
through the term the "Hollywood Principle,"
which basically means "Don't call me, I'll call
you."
• We will discuss IOC in detail later..
Copyright(c) Oded Nissan 2010
The IOC Container
• The IOC Container is the core of Spring’s
framework.
• It is a container that supplies a factory to access
and create Java Beans.
• The Java beans contain application code which
does not depend on the Spring framework.
• The IOC container takes responsibility for object
instantiation, it can also support important
creational patterns such as singletons,
prototypes, and object pools.
Copyright(c) Oded Nissan 2010
Aspect Oriented Programming
Framework
• AOP enables us to capture the cross-cutting code
in modules such as interceptors that can be
applied declaratively wherever the concern they
express applies — without imposing tradeoffs on
the objects benefiting from the services.
• Spring AOP allows the proxying of interfaces or
classes. It provides an extensible pointcut model,
enabling identification of which sets of method to
advise
Copyright(c) Oded Nissan 2010
Data access Abstraction.
• Spring provides an abstraction layer over JDBC
that is significantly simpler and less error-prone
to use than JDBC when you need to use SQLbased access to relational databases.
• The ORM module provides integration layers for
popular object-relational mapping APIs, including
JPA, Hibernate and JDO. Using the ORM package
you can use all those O/R-mappers in
combination with all the other features Spring
offers, such as the simple declarative transaction
management feature mentioned previously.
Copyright(c) Oded Nissan 2010
Data access Abstraction.
• Spring provides support for sending and receiving
JMS messages in a much simpler way than
provided through standard JEE.
• JMX support: Spring supports JMX management
of application objects it configures.
• The OXM module provides an abstraction layer
that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX
and XStream.
Copyright(c) Oded Nissan 2010
Transaction management.
• Spring supports one of the key features of the
EJB model- declarative transactions:
– With declarative transaction management, the
transactional behavior of beans is managed by the
container.
– Declarative transaction management reduces the
complexity of transactions for application
developers and makes it easier to create robust
transactional applications.
Copyright(c) Oded Nissan 2010
Transaction management
• Spring supports Declarative Transaction
management through the use of AOP.
• Spring’s transaction module can work with JTA
transactions or local transactions using JDBC,
JPA, Hibernate or JDO by simply adjusting the
configuration files.

Copyright(c) Oded Nissan 2010
MVC Web Framework.
• Spring provides a web framework based on
the Model-View-Controller (MVC) paradigm.
• Spring MVC provides out-of-the-box
implementations of workflow typical to web
applications. It is highly flexible, allowing you
to use a variety of different view technologies.
It also enables you to fully integrate with your
Spring-based, middle-tier logic through the
use of the Dependency Injection
Copyright(c) Oded Nissan 2010
The MVC Pattern
•

•
•

The Model View Controller pattern provides
a clean separation between the presentation
logic and business logic.
The MVC pattern is the foundation of most
web frameworks.
Can be implemented by mixing Servlets JSPs
and Java Beans.

Copyright(c) Oded Nissan 2010
The MVC Pattern

Copyright(c) Oded Nissan 2010
The MVC Pattern
•
•
•
•

The view part of the MVC pattern is usually
implemented using a JSP page.
A Java Bean represents the model part.
The controller is represented by a Servlet.
Business logic is implemented by Java classes
or EJBs that are invoked by the controller
servlet.

Copyright(c) Oded Nissan 2010
Integration
• Spring supplies integration with various JEE
technologies:
– Web Services
– EJB
– JCA
– JMX

• Remoting framework over HTTP.
• Task Execution and Scheduling.
Copyright(c) Oded Nissan 2010
Summary
• What did we discuss ?
– Spring Introduction
– Spring Architecture
– The Spring Framework Components

Copyright(c) Oded Nissan 2010
Questions ?

Copyright(c) Oded Nissan 2010
Dependency Injection and the
IOC Container

Copyright(c) Oded Nissan 2010
Dependency Injection and the IOC
Container
•
•
•
•
•

What is dependency injection?
IOC container overview
Working with Spring beans
Managing dependencies
Advanced features

Copyright(c) Oded Nissan 2010
What is dependency injection?
• Dependency Injection is a form of push
configuration; the container "pushes"
dependencies into application objects at
runtime.
• This is the opposite of traditional pull
configuration, in which the application object
"pulls" dependencies from its environment.

Copyright(c) Oded Nissan 2010
What is dependency injection?
• Also called Inversion of control and the
Hollywood pattern (“Don’t call me I’ll call
you”).
• Dependency injection can be implemented
with or without a framework.
• The framework simplifies and automates the
injection of dependencies.

Copyright(c) Oded Nissan 2010
What is dependency injection?
An example and discussion. •

Copyright(c) Oded Nissan 2010
Advantages of Dependency Injection
• Application classes are self-documenting, and
dependencies are explicit
• No lock-in to a particular framework, or
proprietary code.
• Greater flexibility in managing configurations.
• Code focuses on application logic, rather than
dependency management or infrastructure.
• Unit testing is easier.
Copyright(c) Oded Nissan 2010
Dependency Injection Frameworks
• Some frameworks deal only with dependency
injections. Some of the popular dependency
injection frameworks (besides Spring):
– Google Guice.
– Pico Container
– JMock
– JEE 5 and JEE 6 provide limited dependency
injection.

Copyright(c) Oded Nissan 2010
IOC Container Overview
• The IoC container and is responsible for
instantiating, configuring, and assembling
beans.
• It gets its instructions on which objects to
instantiate, configure, and assemble by
reading configuration metadata.
• The configuration metadata is represented in
XML, Java annotations, or Java code.
Copyright(c) Oded Nissan 2010
IOC Container Overview
• The BeanFactory interface provides an advanced
configuration mechanism capable of managing
any type of object.
• ApplicationContext is a sub-interface of
BeanFactory. It adds easier integration with
Spring's AOP features; message resource handling
(for use in internationalization), event
publication; and application-layer specific
contexts such as the WebApplicationContext for
use in web applications.
• Usually we will work with the Applicationcontext.
Copyright(c) Oded Nissan 2010
IOC Container Overview

Copyright(c) Oded Nissan 2010
IOC Container Overview
The following is an example of a Spring XML configuration file:

Each Bean has an id and a class attribute.
The id attribute is a string that you use to identify the individual bean
definition. The class attribute defines the type of the bean and uses the
fully qualified classname.

Copyright(c) Oded Nissan 2010
Instantiating a Container
• The container can be instantiated with an XML
file that can be either on a specific file system
path,URL or the classpath.
• We will usually prefer the classpath
mechanism.

Copyright(c) Oded Nissan 2010
Instantiating a Container

Copyright(c) Oded Nissan 2010
IOC Container Configuration
• Besides using several configuration files for
the same container, configuration files can be
included in other configuration files using the
“import” tag:

Copyright(c) Oded Nissan 2010
Working with Beans
• Use the getBean() method on the container to
retrieve beans.
• You can also supply the class as a parameter
and avoid the cast on the returned object:

Copyright(c) Oded Nissan 2010
Instantiating Beans
• To instantiate a bean, initialize the IOC
container and call the getBean() method of
the container to retrieve the bean:

Copyright(c) Oded Nissan 2010
Working with Beans
• Spring beans have the following properties:
–
–
–
–
–
–
–
–
–
–
–

id
name
class
scope
constructor args
properties
autowire mode
init-method
destroy-method
lazy initialization
dependency check
Copyright(c) Oded Nissan 2010
Working with Beans
• Beans are be identified with the “id” or
“name” attributes.
• The “id” attribute is a real XML id, so it can be
validated by the XML parser for uniqueness.
• However there are some limitation on the
valid characters in an XML id. In that case the
“name” attribute is an alternative.
• The “id” tag is the preferred way of identifying
beans.
Copyright(c) Oded Nissan 2010
Using a Factory
• Beans can also be instantiated using a factory.
• You can define a bean with a static factory
method. Use the class attribute to specify the
class containing the static factory method and
an attribute named factory-method to specify
the name of the factory method.
• Instantiation with an instance factory method
invokes a non-static method of an existing
bean from the container to create a new bean.
Copyright(c) Oded Nissan 2010
Using a Factory
• Using a static factory:

• Using an instance factory:

Copyright(c) Oded Nissan 2010
Working with Beans
• Dependency injection comes with two flavors:
– Setter based dependency injection- dependencies
are injected using setter methods.
– Constructor based dependency injection –
dependencies are injected as parameters to the
bean constructor.
– We will usually prefer to use setter based
dependency injection, since it is easier to
maintain.
Copyright(c) Oded Nissan 2010
Setter based Dependency injection
• Initializing a bean using XML:

• Retrieving the bean:

Copyright(c) Oded Nissan 2010
Setter based Dependency injection
• The bean class includes the appropriate
getters and setters for the properties:

Copyright(c) Oded Nissan 2010
Constructor based Dependency
Injection
• The argument is supplied to the constructor in the XML
file. The appropriate constructor is defined in the bean:

Copyright(c) Oded Nissan 2010
Constructor based Dependency
Injection
• Sometimes it is necessary to specify the
argument types to prevent ambiguity.
• If a bean has two constructors, one accepting a
String and the other accepting an int, the
container might not recognize which constructor
we want to invoke.
• The values specified as arguments or properties
are converted from a string type to the correct
type in the bean using Spring PropertyEditors.

Copyright(c) Oded Nissan 2010
Constructor based Dependency
Injection
• For example, see the constructors of
SampleBean:

• And the XML definition:

Copyright(c) Oded Nissan 2010
Constructor based Dependency
Injection
• In this case we need to specify the argument
type to the container to prevent ambiguity:

• We can also specify the argument position
when the constructor has multiple arguments:

Copyright(c) Oded Nissan 2010
Dependency Injection
• Spring’s dependency injection framework
allows injecting the following types:
– Primitive values
– References to other beans
– Collections

Copyright(c) Oded Nissan 2010
Dependency Injection
• Injecting beans using method injection:

Copyright(c) Oded Nissan 2010
Dependency Injection
• Injecting beans using constructor injection:

Copyright(c) Oded Nissan 2010
Collections Dependency Injection
• You can use the <list>, <map> and <props> to
inject collections into beans.

Copyright(c) Oded Nissan 2010
Collections Dependency Injection
• As of Spring 2.0, the container supports the
merging of collections. An application developer
can define a parent-style <list/>, <map/>, <set/>
or <props/> element, and have child-style <list/>,
<map/>, <set/> or <props/> elements inherit and
override values from the parent collection.
• The child collection's values are the result of
merging the elements of the parent and child
collections, with the child's collection elements
overriding values specified in the parent
collection.
Copyright(c) Oded Nissan 2010
Collections Dependency Injection
• Collections Merging:

Copyright(c) Oded Nissan 2010
Exercise

Copyright(c) Oded Nissan 2010
Injecting Empty Values
• Spring can inject empty values using an empty
string or a <null> element:

Copyright(c) Oded Nissan 2010
Aliasing Beans
• You can provide an alias name for an existing
bean.
• This is useful in case we need to use beans
that exist in a different subsystem.
• The bean is mapped from the name to the
alias:

Copyright(c) Oded Nissan 2010
Using idref
• The <idref> tag is used to reference other
beans. It is an alternative to the <ref> tag.
• The referenced bean name should be passed
in the <idref> tag. This allows the container to
verify the dependencies at deploy time, rather
than at runtime.

Copyright(c) Oded Nissan 2010
Inner Beans
• A <bean/> element inside the <property/> or
<constructor-arg/> elements defines a socalled inner bean.
• An inner bean is anonymous and is always of
prototype scope.

Copyright(c) Oded Nissan 2010
Depends On
• Sometimes there is a dependency between
beans that is indirect. For example, when one
bean depends on another bean being
initialized before its creation.
• This dependency management is achieved by
using the <depends-on> tag that can explicitly
force one or more beans to be initialized
before the bean using this element is
initialized.
Copyright(c) Oded Nissan 2010
Depends On
• The <depends-on> tag can also specify several
dependencies separated by commas.

Copyright(c) Oded Nissan 2010
Lazy Initialization
• Lazy initialization is used when we want to
load bean properties on demand as they are
accessed by the program.
• This is usually used when initialization is a
costly operation.
• Spring supports lazy initialization of beans by
using the “lazy-init=true” attribute of the
<bean> element.
Copyright(c) Oded Nissan 2010
Autowiring
• Spring is able to use introspection of bean
classes in the factory and perform autowiring
of dependencies.
• In autowiring, you leave the bean property or
constructor argument undeclared (in the XML
file), and Spring will use reflection to find the
type and name of the property, and then
match it to another bean in the factory based
on type or name.
Copyright(c) Oded Nissan 2010
Autowiring
• Autowiring at the bean level is controlled via the use of
the autowire attribute, which has five possible values:
– No – no autowiring Bean properties and constructor
arguments must be explicitly declared.
– byName- Autowiring by property name. Spring looks for a
bean with the same name as the property that needs to be
autowired.
– byType- Autowire by matching type. if there is exactly one
bean in the factory of the same type as the property, the
property value is set as that other bean. If there is more
than one bean in the factory matching the type, it is
considered a fatal error and an exception is raised.
Copyright(c) Oded Nissan 2010
Autowiring
– constructor - Autowire the constructor by type.
This works in essentially identical fashion to how
byType works for properties, except that there
must be exactly one matching bean, by type, in
the factory for each constructor argument.
– autodetect - Choose byType or constructor as
appropriate. The bean is introspected, and if there
is a default no-arg constructor, byType is used,
otherwise, constructor is used.

Copyright(c) Oded Nissan 2010
Autowiring Example

Copyright(c) Oded Nissan 2010
Autowiring Limitations
• Explicit dependencies in property and
constructor-arg settings always override
autowiring.
• You cannot autowire so-called simple
properties such as primitives, Strings, and
Classes (and arrays of such simple properties).
This limitation is by-design.

Copyright(c) Oded Nissan 2010
Autowiring
• Pros:
– Less Spring configuration.
– Configuration can be outdated. Autowiring will ensure
that dependencies are up to date.

• Cons:
– Autowiring is less exact than explicit wiring.
– Wiring information may not be available to tools that
may generate documentation from a Spring container.
– Does not provide the dependency documentation that
explicit wiring does.

Copyright(c) Oded Nissan 2010
Excluding a Bean from Autowiring
• On a per-bean basis, you can exclude a bean from
autowiring. In Spring's XML format, set the
autowire-candidate attribute of the <bean/>
element to false; the container makes that
specific bean definition unavailable to the
autowiring infrastructure.
• You can also limit autowire candidates based on
pattern-matching against bean names. The toplevel <beans/> element accepts one or more
patterns within its default-autowire-candidates
attribute.
Copyright(c) Oded Nissan 2010
Exercise

Copyright(c) Oded Nissan 2010
Bean Scopes
• When you create a bean definition, you create a
recipe for creating actual instances of the class
defined by that bean definition. The idea that a
bean definition is a recipe is important, because it
means that, as with a class, you can create many
object instances from a single recipe.
• Beans can be defined to be deployed in one of a
number of scopes: out of the box, the Spring
Framework supports five scopes, three of which
are available only if you use a web-aware
ApplicationContext.
Copyright(c) Oded Nissan 2010
Bean Scopes
Bean Scop

Description

Singleton

Only one bean is created per container

Prototype

A bean is created with each bean request from the
container

Request

A bean is created for each HTTP request.

Session

A bean is created for each HTTPSession

Global-session

Similar to session and applies only in the context of
portlet-based web applications

Copyright(c) Oded Nissan 2010
The Singleton Scope

Copyright(c) Oded Nissan 2010
The Prototype Scope

Copyright(c) Oded Nissan 2010
Singleton Beans with Prototype
Dependencies
• When you use singleton-scoped beans with
dependencies on prototype beans, be aware that
dependencies are resolved at instantiation time. Thus if
you dependency-inject a prototype-scoped bean into a
singleton-scoped bean, a new prototype bean is
instantiated and then dependency-injected into the
singleton bean. The prototype instance is the sole
instance that is ever supplied to the singleton-scoped
bean.
• Usually this is not what we want. We want to get a new
prototype bean every time we request it from the
singleton bean.

Copyright(c) Oded Nissan 2010
Singleton Beans with Prototype
Dependencies
• One solution to this problem of a prototype
bean in a singleton bean is to get the bean
directly from the container.
• However, that would make the bean
container-aware and would break our
dependency injection framework.
• We can solve the problem a Spring
mechanism called method injection.
Copyright(c) Oded Nissan 2010
Method Injection
• Lookup method injection is the ability of the
container to override methods on container
managed beans, to return the lookup result
for another named bean in the container.
• The Spring Framework implements this
method injection by using bytecode
generation from the CGLIB library to generate
dynamically a subclass that overrides the
method.
Copyright(c) Oded Nissan 2010
Method Injection
• We create the singleton bean, with the
method that lookups the prototype bean as
abstract. With the following signature:
• We then specify the lookup method name in
the bean definition.

Copyright(c) Oded Nissan 2010
Method Injection

Copyright(c) Oded Nissan 2010
Dependency Check
• Sometimes we want to ensure that all properties
are set on a bean.
• The Spring IoC container can check for unresolved
dependencies of a bean deployed into the
container.
• You can enable dependency checking per bean,
just as with the autowiring functionality.
• In XML-based configuration metadata, you
specify dependency checking via the
dependency-check attribute in a bean definition.
Copyright(c) Oded Nissan 2010
Dependency Check
• The dependency-check attribute can have the
following values:
– none – no dependency check will be done.
– simple – dependency check will be done for
primitive types and collections.
– object – dependency checking for other beans.
– all – dependency checking for all bean properties.

Copyright(c) Oded Nissan 2010
Lifecycle Callbacks
• Lifecycle callbacks allow you to interact with
the spring container.
• you can implement the Spring InitializingBean
and DisposableBean interfaces. The container
calls afterPropertiesSet() for the former and
destroy() for the latter to allow the bean to
perform certain actions upon initialization and
destruction of your beans.
Copyright(c) Oded Nissan 2010
Lifecycle Callbacks
Example using callbacks: •

Copyright(c) Oded Nissan 2010
Lifecycle Callbacks
• The problem with the former approach is that
now our bean is dependent on spring specific
interfaces.
• An alternative is to specify the initialization
and destroy callbacks in the spring
configuration using the init-method and
destroy-method bean attributes.

Copyright(c) Oded Nissan 2010
Lifecycle Callbacks
Using init-method: •

• Using destroy-method:

Copyright(c) Oded Nissan 2010
Lifecycle Callbacks
• You can configure the Spring container to look for
named initialization and destroy callback method
names on every bean.
• This means that you, as an application developer,
can write your application classes and use an
initialization callback called init() for each bean,
without configuring it in the XML file.
• This feature also enforces a consistent naming
convention for initialization and destroy method
callbacks.
Copyright(c) Oded Nissan 2010
Lifecycle Callbacks
Example of default lifecycle callbacks: •

Copyright(c) Oded Nissan 2010
Exercise

Copyright(c) Oded Nissan 2010
Container Shutdown Hook
• In a non web environment you can also register a shutdown
hook that will be called when the container is shutdown.
• The shutdown hook will be called when the program’s main
method exits:

Copyright(c) Oded Nissan 2010
Injecting a Spring Context
• Sometimes we will need to access the spring
context from outside the spring container.
• Since we don’t want to create the
ApplicationContext again, we want to inject the
existing ApplicationContext into our class.
• To inject the spring context we write a class that
implements the ApplicationContextAware
interface, define it as a spring bean and provide a
static method to retrieve the context.
Copyright(c) Oded Nissan 2010
Injecting a Spring Context
• Example of a helper class that the context will
be injected to:

Copyright(c) Oded Nissan 2010
Bean Definition Inheritance
• Sometimes we might want to inherit the bean
definition in a child bean.
• A child bean definition inherits configuration
data from a parent definition. The child
definition can override some values, or add
others, as needed.
• This is done by specifying the “parent”
attribute in the child bean configuration.
Copyright(c) Oded Nissan 2010
Bean Definition Inheritance
• Note that bean definition inheritance does not
necessarily imply class inheritance.
• We can use bean definition inheritance with
or without class inheritance.
• We can also use class inheritance with or
without bean definition inheritance.

Copyright(c) Oded Nissan 2010
Bean Definition Inheritance
• Bean definition inheritance example:

Copyright(c) Oded Nissan 2010
Externalizing Properties
• You use the PropertyPlaceholderConfigurer to
externalize property values from a bean
definition into another separate file in the
standard Java Properties format.
• Doing so enables the person deploying an
application to customize environment-specific
properties such as database URLs and passwords,
without the complexity or risk of modifying the
main XML definition file or files for the container.
Copyright(c) Oded Nissan 2010
Externalizing Properties
• This mechanism is called the
PropertyPlaceholderConfigurator. To use it:
– Specify placeholders for externalized properties in
the bean definition:

Copyright(c) Oded Nissan 2010
Externalizing Properties
– Define the properties to be replaced and their
replace values in a properties file:

– Use the configuration to have the context load the
properties file:

Copyright(c) Oded Nissan 2010
Exercise

Copyright(c) Oded Nissan 2010
Internationalization
• The ApplicationContext interface extends an interface
called MessageSource, to provide internationalization
(i18n) functionality.
• Spring also provides the interface
HierarchicalMessageSource, which can resolve messages
hierarchically.
• The basic method to retrieve message is:
– String getMessage(String code, Object[] args, String default,
Locale loc)

• When no message is found for the specified locale, the
default message is used.
• Additional flavors of the getMessage method are available.

Copyright(c) Oded Nissan 2010
Internationalization
• When an ApplicationContext is loaded, it automatically
searches for a MessageSource bean defined in the context.
• The bean must have the name messageSource. If such a
bean is found, all calls to the preceding methods are
delegated to the message source.
• If no message source is found, the ApplicationContext
attempts to find a parent containing a bean with the same
name. If it does, it uses that bean as the MessageSource.
• If the ApplicationContext cannot find any source for
messages, an empty DelegatingMessageSource is
instantiated in order to be able to accept calls to the
methods defined above.

Copyright(c) Oded Nissan 2010
Internationalization
• Spring provides two MessageSource implementations,
ResourceBundleMessageSource and
StaticMessageSource. Both implement
HierarchicalMessageSource.
• ResourceBundleMessageSource example:

Copyright(c) Oded Nissan 2010
Internationalization
• The example assumes we have three different
resource bundles called format, exceptions
and windows.
• Spring's various MessageResource
implementations follow the same locale
resolution and fallback rules as the standard
JDK ResourceBundle.
• The locale is appended to the file name, the
suffix is “properties”.
Copyright(c) Oded Nissan 2010
Internationalization
• For example, messages for the hebrew locale
will be stored in a files called
format_he.properties.
• The country code can also be appended for
example: format_he_IL.properties.
• The default locale is named format.properties.
• We need to specify the locale so when
retrieving the message.
Copyright(c) Oded Nissan 2010
Internationalization
Bundle files: •

• Retrieving the messages using the ApplicationContext
(Note that ApplicationContext also implements
MessageSource):

Copyright(c) Oded Nissan 2010
Summary
• What did we discuss ?
– What is dependency injection?
– IOC container overview
– Working with Spring beans
– Managing dependencies
– Advanced features

Copyright(c) Oded Nissan 2010
Questions ?

Copyright(c) Oded Nissan 2010
Resources

Copyright(c) Oded Nissan 2010
Resources
•
•
•
•
•

Available Resource implementations
The Resource Loader
Injecting Resources
ApplicationContext and Resources
Resources and Wildcards

Copyright(c) Oded Nissan 2010
Resources
• Spring contains various resource
implementations that support retrieving
resources from difference sources.
• The possible sources include the filesystem,
the classpath, URLs and the ServletContext.
• All resource implementations implement the
Resource interface.

Copyright(c) Oded Nissan 2010
Resources
• The Resource Interface:

Copyright(c) Oded Nissan 2010
Resources
• The following resource implementations are
supported by Spring:
– URLResource
– ClassPathResource
– FileSystemResource
– ServletContextResource
– InputStreamResource
– ByteArrayResource

Copyright(c) Oded Nissan 2010
Resources
• Resources are loaded by a ResourceLoader, there are
various implementations of the ResourceLoader
interface that support loading different resources.
• All application contexts implement the ResourceLoader
interface, and therefore all application contexts may be
used to obtain Resource instances.

Copyright(c) Oded Nissan 2010
Resources
• When you call getResource() on a specific
application context, and the location path
specified doesn't have a specific prefix, you
will get back a Resource type that is
appropriate to that particular application
context. For example this would return a
ClassPathResource :

Copyright(c) Oded Nissan 2010
Resources
• You can also force ClassPathResource to be
used, regardless of the application context
type, by specifying the special classpath:
prefix:
• Or a url prefix or file prefix:

Copyright(c) Oded Nissan 2010
Injecting Resources
• Resources can also be injected to beans using
dependency injection. When the property is of
a resource type the values will be used to
initialize the appropriate resource. In the
following examples the appropriate resource
type will be initialized:

Copyright(c) Oded Nissan 2010
Application Contexts and Resources
• The constructor of an ApplicationContext
takes a path String as a parameter and uses
the appropriate resource loader for the
specific ApplicationContext implementation
used. For example:

Copyright(c) Oded Nissan 2010
Resources and Wildcards
• Resource paths may contain the special
"classpath*:" prefix and/or internal Ant-style
regular expressions.
• One use for this mechanism is when doing
component-style application assembly. All
components can 'publish' context definition
fragments to a well-known location path, and
all of them will be picked up by the
applicationcontext using wildcards.
Copyright(c) Oded Nissan 2010
Resources and Wildcards
• Ant style regular expression examples:

• In this example all resources matching the
regular expressions will be loaded.

Copyright(c) Oded Nissan 2010
Resources and Wildcards
• Using the classpath*: prefix :

• In this example all resources found in the
classpath with the “conf/appContext.xml”
path will be loaded.

Copyright(c) Oded Nissan 2010
Exercise

Copyright(c) Oded Nissan 2010
Summary
• What did we discuss ?
– Available Resource implementations
– The Resource Loader
– Injecting Resources
– ApplicationContext and Resources
– Resources and Wildcards

Copyright(c) Oded Nissan 2010
Questions ?

Copyright(c) Oded Nissan 2010
Spring AOP

Copyright(c) Oded Nissan 2010
Spring AOP
•
•
•
•
•

What is AOP ?
AOP Concepts
Spring AOP options
Example
Summary

Copyright(c) Oded Nissan 2010
What is AOP ?
• Aspect-Oriented Programming (AOP) is an
important technology, well-suited to solving
many common problems. Spring offers AOP
features to complement its IoC features and
ensure that enterprise service code does not
pollute your application objects.
• Spring takes a pragmatic approach to AOP. You
can use as little AOP as you want, or integrate
with AspectJ to harness the power of AOP
extensions to the Java language.
Copyright(c) Oded Nissan 2010
AOP Concepts
• Aspect: a modularization of a concern that cuts
across multiple classes.
• Join point: a point during the execution of a
program, such as the execution of a method or
the handling of an exception.
• Advice: action taken by an aspect at a particular
join point.
• Pointcut: a predicate that matches join points.
Advice is associated with a pointcut expression
and runs at any join point matched by the
pointcut
Copyright(c) Oded Nissan 2010
AOP Concepts
• Introduction- declaring additional methods or
fields on behalf of a type.
• Target object- object being advised by one or
more aspects.
• AOP proxy- an object created by the AOP
framework in order to implement the aspect
contracts.
• Weaving - linking aspects with other application
types or objects to create an advised object.
Copyright(c) Oded Nissan 2010
Advice Types
• Before advice- Advice that executes before a join
point.
• After returning advice- Advice to be executed
after a join point completes normally.
• After throwing advice- Advice to be executed if a
method exits by throwing an exception.
• After (finally) advice- Advice to be executed
regardless of the means by which a join point
exits.
• Around advice- Advice that surrounds a join point
such as a method invocation.
Copyright(c) Oded Nissan 2010
Spring AOP
• Spring AOP is implemented in pure Java. There
is no need for a special compilation process.
• One of the central tenets of the Spring
Framework is that of non-invasiveness; this is
the idea that you should not be forced to
introduce framework-specific classes and
interfaces into your business/domain model.

Copyright(c) Oded Nissan 2010
AOP Proxies
• Spring AOP defaults to using standard J2SE
dynamic proxies for AOP proxies. This enables
any interface to be proxied.
• Spring AOP can also use CGLIB proxies. This is
necessary to proxy classes, rather than
interfaces. CGLIB is used by default if a
business object does not implement an
interface.
Copyright(c) Oded Nissan 2010
AOP Proxies
• When using dynamic proxies, a proxy object is
generated on the fly for the proxied object.
The proxy object then intercepts the method
calls on the real object.
• The proxy can then advices on the object and
also invoke the real method on the real object.

Copyright(c) Oded Nissan 2010
AOP Proxies
• Spring provides an API to programmatically apply
dynamic proxies to objects.
• Here we can see the “foo” method intercepted by
the proxy:

Copyright(c) Oded Nissan 2010
Spring AOP
• There are currently 3 options for using Spring
AOP:
– @AspectJ style annotations.
– Schema based AOP support
– Old Spring AOP APIs (prior to version 2.0)

Copyright(c) Oded Nissan 2010
@AspectJ Support
• @AspectJ refers to a style of declaring aspects
as regular Java classes annotated with Java 5
annotations.
• Spring 2.0 interprets the same annotations as
AspectJ 5, using a library supplied by AspectJ
for pointcut parsing and matching.
• The AOP runtime is still pure Spring AOP
though, and there is no dependency on the
AspectJ compiler or weaver.
Copyright(c) Oded Nissan 2010
Schema based AOP Support
• Spring also offers support for defining aspects
using the new "aop" namespace tags.
• The exact same pointcut expressions and
advice kinds are supported as when using the
@AspectJ style.
• Definitions will be done in XML rather than in
annotations.

Copyright(c) Oded Nissan 2010
AspectJ@ vs. schema based AOP
• XML can be used with any Java version.
• XML can be changed without changing and
compiling code.
• AspectJ@ annotations unite the code with the
configuration.
• The @AspectJ style supports additional
instantiation models, and richer pointcut
composition.
• We will discuss only schema based AOP.
Copyright(c) Oded Nissan 2010
Using AOP
• To use Spring AOP:
– Write a bean with your advice methods.
– Declare the bean to be an aspect.
– Specify the pointcut to which the aspect will be
applied in the configuration file.
– Specify the advice to be applied to the pointcut in
the configuration file.

Copyright(c) Oded Nissan 2010
Spring AOP Pointcut expressions
• execution - for matching method execution join points, this is the
primary pointcut designator you will use when working with Spring
AOP
• within - limits matching to join points within certain types (simply
the execution of a method declared within a matching type when
using Spring AOP)
• this - limits matching to join points (the execution of methods when
using Spring AOP) where the bean reference (Spring AOP proxy) is
an instance of the given type
• target - limits matching to join points (the execution of methods
when using Spring AOP) where the target object (application object
being proxied) is an instance of the given type

Copyright(c) Oded Nissan 2010
Spring AOP Pointcut expressions
• args - limits matching to join points (the execution of methods
when using Spring AOP) where the arguments are instances of the
given types
• @target - limits matching to join points (the execution of methods
when using Spring AOP) where the class of the executing object has
an annotation of the given type
• @args - limits matching to join points (the execution of methods
when using Spring AOP) where the runtime type of the actual
arguments passed have annotations of the given type(s)
• @within - limits matching to join points within types that have the
given annotation (the execution of methods declared in types with
the given annotation when using Spring AOP)
• @annotation - limits matching to join points where the subject of
the join point (method being executed in Spring AOP) has the given
annotation

Copyright(c) Oded Nissan 2010
AOP Pointcut Expressions
• Execution of any public method.
• Execution of any method in the AccountService interface.

• Execution of any method in the service package.
• Execution of any method in the service package or any
of its subpackages

Copyright(c) Oded Nissan 2010
AOP Pointcut Expressions
• Any joinpoint within the service package.
• Any join point where the proxy implements the AccountService
interface.
• Any join point where the target object implements the
AccountService interface.

• Any join point with a single parameter of type Serializable.

Copyright(c) Oded Nissan 2010
Spring AOP Example
• We want to profile a method execution by
measuring the time it takes to execute the
method.
• We define the SimpleProfiler class as an
aspect.
• We apply an around advice to the getFoo
method in theFooService interface.

Copyright(c) Oded Nissan 2010
Spring AOP Example
• We define a FooService interface and
implement it.

Copyright(c) Oded Nissan 2010
Spring AOP Example
• We write the SimpleProfiler class which will
serve as the aspect. We write the profile
method as an around advice.

Copyright(c) Oded Nissan 2010
Spring AOP Example
• We use XML configuration to apply the advice
of the SimpleProfiler aspect to the FooService
interface.

Copyright(c) Oded Nissan 2010
Spring AOP Example
• The following is a test driver invoking the bean
the aspect was applied on and the resulting
output.

Copyright(c) Oded Nissan 2010
Exercise

Copyright(c) Oded Nissan 2010
Spring Best Practices
•
•
•
•

Prefer setter based injection.
Use naming conventions for beans.
Try to avoid using autowiring.
Carefully check the need for prototype scope
beans.
• Reuse bean definitions when possible.
• Use AOP carefully.
• Not every class is a Spring bean
Copyright(c) Oded Nissan 2010
Summary
• What did we discuss ?
– What is AOP ?
– AOP Concepts
– Spring AOP options
– Example

Copyright(c) Oded Nissan 2010

Más contenido relacionado

La actualidad más candente

Future of Java EE with Java SE 8
Future of Java EE with Java SE 8Future of Java EE with Java SE 8
Future of Java EE with Java SE 8Hirofumi Iwasaki
 
Server Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David DelabasseeServer Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David DelabasseeJAXLondon2014
 
A Java Implementer's Guide to Better Apache Spark Performance
A Java Implementer's Guide to Better Apache Spark PerformanceA Java Implementer's Guide to Better Apache Spark Performance
A Java Implementer's Guide to Better Apache Spark PerformanceTim Ellison
 
JSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworksJSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworksDmitry Kornilov
 
Oracle ADF Architecture TV - Development - Programming Best Practices
Oracle ADF Architecture TV - Development - Programming Best PracticesOracle ADF Architecture TV - Development - Programming Best Practices
Oracle ADF Architecture TV - Development - Programming Best PracticesChris Muir
 
Oracle ADF Architecture TV - Design - Architecting for ADF Mobile Integration
Oracle ADF Architecture TV - Design - Architecting for ADF Mobile IntegrationOracle ADF Architecture TV - Design - Architecting for ADF Mobile Integration
Oracle ADF Architecture TV - Design - Architecting for ADF Mobile IntegrationChris Muir
 
Oracle ADF Architecture TV - Design - ADF BC Application Module Design
Oracle ADF Architecture TV - Design - ADF BC Application Module DesignOracle ADF Architecture TV - Design - ADF BC Application Module Design
Oracle ADF Architecture TV - Design - ADF BC Application Module DesignChris Muir
 
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project LayoutsOracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project LayoutsChris Muir
 
Introduction to Sightly and Sling Models
Introduction to Sightly and Sling ModelsIntroduction to Sightly and Sling Models
Introduction to Sightly and Sling ModelsStefano Celentano
 
Oracle ADF Architecture TV - Deployment - Build Options
Oracle ADF Architecture TV - Deployment - Build OptionsOracle ADF Architecture TV - Deployment - Build Options
Oracle ADF Architecture TV - Deployment - Build OptionsChris Muir
 
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesJavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesMert Çalışkan
 
Spring intro classes-in-mumbai
Spring intro classes-in-mumbaiSpring intro classes-in-mumbai
Spring intro classes-in-mumbaivibrantuser
 
Oracle ADF Architecture TV - Design - ADF Architectural Patterns
Oracle ADF Architecture TV - Design - ADF Architectural PatternsOracle ADF Architecture TV - Design - ADF Architectural Patterns
Oracle ADF Architecture TV - Design - ADF Architectural PatternsChris Muir
 
Apache Harmony: An Open Innovation
Apache Harmony: An Open InnovationApache Harmony: An Open Innovation
Apache Harmony: An Open InnovationTim Ellison
 
Oracle ADF Architecture TV - Design - Project Dependencies
Oracle ADF Architecture TV - Design - Project DependenciesOracle ADF Architecture TV - Design - Project Dependencies
Oracle ADF Architecture TV - Design - Project DependenciesChris Muir
 
Oracle ADF Architecture TV - Design - Task Flow Navigation Options
Oracle ADF Architecture TV - Design - Task Flow Navigation OptionsOracle ADF Architecture TV - Design - Task Flow Navigation Options
Oracle ADF Architecture TV - Design - Task Flow Navigation OptionsChris Muir
 

La actualidad más candente (19)

Future of Java EE with Java SE 8
Future of Java EE with Java SE 8Future of Java EE with Java SE 8
Future of Java EE with Java SE 8
 
Server Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David DelabasseeServer Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David Delabassee
 
Spring
SpringSpring
Spring
 
JSF 2.2
JSF 2.2JSF 2.2
JSF 2.2
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
A Java Implementer's Guide to Better Apache Spark Performance
A Java Implementer's Guide to Better Apache Spark PerformanceA Java Implementer's Guide to Better Apache Spark Performance
A Java Implementer's Guide to Better Apache Spark Performance
 
JSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworksJSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworks
 
Oracle ADF Architecture TV - Development - Programming Best Practices
Oracle ADF Architecture TV - Development - Programming Best PracticesOracle ADF Architecture TV - Development - Programming Best Practices
Oracle ADF Architecture TV - Development - Programming Best Practices
 
Oracle ADF Architecture TV - Design - Architecting for ADF Mobile Integration
Oracle ADF Architecture TV - Design - Architecting for ADF Mobile IntegrationOracle ADF Architecture TV - Design - Architecting for ADF Mobile Integration
Oracle ADF Architecture TV - Design - Architecting for ADF Mobile Integration
 
Oracle ADF Architecture TV - Design - ADF BC Application Module Design
Oracle ADF Architecture TV - Design - ADF BC Application Module DesignOracle ADF Architecture TV - Design - ADF BC Application Module Design
Oracle ADF Architecture TV - Design - ADF BC Application Module Design
 
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project LayoutsOracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
 
Introduction to Sightly and Sling Models
Introduction to Sightly and Sling ModelsIntroduction to Sightly and Sling Models
Introduction to Sightly and Sling Models
 
Oracle ADF Architecture TV - Deployment - Build Options
Oracle ADF Architecture TV - Deployment - Build OptionsOracle ADF Architecture TV - Deployment - Build Options
Oracle ADF Architecture TV - Deployment - Build Options
 
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesJavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
 
Spring intro classes-in-mumbai
Spring intro classes-in-mumbaiSpring intro classes-in-mumbai
Spring intro classes-in-mumbai
 
Oracle ADF Architecture TV - Design - ADF Architectural Patterns
Oracle ADF Architecture TV - Design - ADF Architectural PatternsOracle ADF Architecture TV - Design - ADF Architectural Patterns
Oracle ADF Architecture TV - Design - ADF Architectural Patterns
 
Apache Harmony: An Open Innovation
Apache Harmony: An Open InnovationApache Harmony: An Open Innovation
Apache Harmony: An Open Innovation
 
Oracle ADF Architecture TV - Design - Project Dependencies
Oracle ADF Architecture TV - Design - Project DependenciesOracle ADF Architecture TV - Design - Project Dependencies
Oracle ADF Architecture TV - Design - Project Dependencies
 
Oracle ADF Architecture TV - Design - Task Flow Navigation Options
Oracle ADF Architecture TV - Design - Task Flow Navigation OptionsOracle ADF Architecture TV - Design - Task Flow Navigation Options
Oracle ADF Architecture TV - Design - Task Flow Navigation Options
 

Similar a Introduction to spring

WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1odedns
 
Asp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareAsp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareRitwik Das
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to SpringSujit Kumar
 
Oracle ADF Overview for Beginners
Oracle ADF Overview for BeginnersOracle ADF Overview for Beginners
Oracle ADF Overview for BeginnersJithin Kuriakose
 
Spring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsSpring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsVirtual Nuggets
 
How Spring Framework Really Works?
How Spring Framework Really Works?How Spring Framework Really Works?
How Spring Framework Really Works?NexSoftsys
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworksMukesh Kumar
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overviewodedns
 
Burns jsf-confess-2015
Burns jsf-confess-2015Burns jsf-confess-2015
Burns jsf-confess-2015Edward Burns
 
TheSpringFramework
TheSpringFrameworkTheSpringFramework
TheSpringFrameworkShankar Nair
 
Oracle ADF (Application Development Framework) for Forms, Developers Slides
Oracle ADF (Application Development Framework) for Forms, Developers SlidesOracle ADF (Application Development Framework) for Forms, Developers Slides
Oracle ADF (Application Development Framework) for Forms, Developers SlidesSafi Ur Rehman
 
Oracle ad fforformsdevelopers_slides
Oracle ad fforformsdevelopers_slidesOracle ad fforformsdevelopers_slides
Oracle ad fforformsdevelopers_slidesYogesh Sharma
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
Essential Kit for Oracle JET Programming
Essential Kit for Oracle JET ProgrammingEssential Kit for Oracle JET Programming
Essential Kit for Oracle JET Programmingandrejusb
 

Similar a Introduction to spring (20)

Java Spring
Java SpringJava Spring
Java Spring
 
WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Asp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareAsp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech Software
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 
Oracle ADF Overview for Beginners
Oracle ADF Overview for BeginnersOracle ADF Overview for Beginners
Oracle ADF Overview for Beginners
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework Rohit
 
Spring
SpringSpring
Spring
 
Spring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsSpring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggets
 
How Spring Framework Really Works?
How Spring Framework Really Works?How Spring Framework Really Works?
How Spring Framework Really Works?
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworks
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overview
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Burns jsf-confess-2015
Burns jsf-confess-2015Burns jsf-confess-2015
Burns jsf-confess-2015
 
spring
springspring
spring
 
TheSpringFramework
TheSpringFrameworkTheSpringFramework
TheSpringFramework
 
Oracle ADF (Application Development Framework) for Forms, Developers Slides
Oracle ADF (Application Development Framework) for Forms, Developers SlidesOracle ADF (Application Development Framework) for Forms, Developers Slides
Oracle ADF (Application Development Framework) for Forms, Developers Slides
 
Oracle ad fforformsdevelopers_slides
Oracle ad fforformsdevelopers_slidesOracle ad fforformsdevelopers_slides
Oracle ad fforformsdevelopers_slides
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Essential Kit for Oracle JET Programming
Essential Kit for Oracle JET ProgrammingEssential Kit for Oracle JET Programming
Essential Kit for Oracle JET Programming
 

Último

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Introduction to spring

  • 2. Introduction to Spring • • • • • • Introduction About the Lecturer Topics Exercises Agenda Questions ? Copyright(c) Oded Nissan 2010
  • 3. Introduction to Spring • • • • • • Introduction About the Lecturer Topics Exercises Agenda Questions ? Copyright(c) Oded Nissan 2010
  • 4. Agenda • • • • • Spring architecture and overview Dependency Injection and the IOC Container Resources Spring AOP Summary Copyright(c) Oded Nissan 2010
  • 5. Spring architecture and overview • Spring Introduction • Spring Architecture • The Spring Framework Components Copyright(c) Oded Nissan 2010
  • 6. Dependency Injection and the IOC Container • • • • • What is dependency injection? IOC container overview Working with Spring beans Managing dependencies Advanced features Copyright(c) Oded Nissan 2010
  • 7. Resources • • • • • Available Resource implementations The Resource Loader Injecting Resources ApplicationContext and Resources Resources and Wildcards Copyright(c) Oded Nissan 2010
  • 8. Spring AOP • • • • • What is AOP ? AOP Concepts Spring AOP options Example Summary Copyright(c) Oded Nissan 2010
  • 9. Spring architecture and overview Copyright(c) Oded Nissan 2010
  • 10. Spring architecture and overview • Spring Introduction • Spring Architecture • The Spring Framework Components Copyright(c) Oded Nissan 2010
  • 11. Resources • http://www.springsource.org - the home of the Spring Framework. • http://www.springhub.com – a hub for Spring resources. • http://static.springsource.org/spring/docs/curren t/spring-framework-reference/html/ - the Spring Framework reference documentation. • http://static.springsource.org/spring/docs/3.0.x/j avadoc-api/ - Spring API docs. • http://opensource.atlassian.com/confluence/spri ng/dashboard.action - Spring community wiki. Copyright(c) Oded Nissan 2010
  • 12. Spring Introduction • What Is Spring ? – The Spring Framework is an open source application framework that aims to make JEE development easier. – Popular open source framework – Based on the dependency injection pattern – Developed by Rod Johnson in 2004 – Current version is 3.0 Copyright(c) Oded Nissan 2010
  • 13. Why do we need Spring ? • • • • JEE is too complex and too tightly coupled. An alternative to the complex EJB technology. JEE is based on tools and code generators. Lightweight framework that does not need a full JEE server to run. • Better performance. • JEE is hard to unit test. Copyright(c) Oded Nissan 2010
  • 14. Spring Principles • Spring is a non-invasive framework. • Spring provides a consistent programming model, usable in any environment • Spring aims to promote code reuse. • Spring aims to facilitate Object Oriented design in JEE applications • Spring aims to facilitate good programming practice, such as programming to interfaces, rather than classes Copyright(c) Oded Nissan 2010
  • 15. Spring Principles • Spring promotes plugability • Spring facilitates the extraction of configuration values from Java code into XML or properties files. • Spring is designed so that applications using it are as easy as possible to test • Spring is consistent • Spring promotes architectural choice • Spring does not reinvent the wheel Copyright(c) Oded Nissan 2010
  • 16. Spring Architecture • • • • Spring is designed as a modular framework. Modules as separate and not tightly coupled. Compatible with all application servers. Easy integration into JEE or stand alone Java applications. Copyright(c) Oded Nissan 2010
  • 18. Spring Usage Scenarios • One of the advantages of spring is that it’s not a “take it or leave it” framework. • Not all spring modules need to be used. • Spring modules can be easily integrated with other frameworks. • Spring also provides simplified APIs to JEE services. Copyright(c) Oded Nissan 2010
  • 19. Full Spring Web application Copyright(c) Oded Nissan 2010
  • 20. Spring as a Middle Tier Copyright(c) Oded Nissan 2010
  • 21. Spring as a Remoting Framework Copyright(c) Oded Nissan 2010
  • 22. Spring Framework Components • • • • • • IOC Container. Aspect Oriented Programming Framework. Data access abstraction. Transaction management. MVC web framework. Integration Copyright(c) Oded Nissan 2010
  • 23. The IOC Container • The technology that Spring is most identified with is Inversion of Control, and specifically the Dependency Injection flavor of Inversion of Control. • Inversion of Control is best understood through the term the "Hollywood Principle," which basically means "Don't call me, I'll call you." • We will discuss IOC in detail later.. Copyright(c) Oded Nissan 2010
  • 24. The IOC Container • The IOC Container is the core of Spring’s framework. • It is a container that supplies a factory to access and create Java Beans. • The Java beans contain application code which does not depend on the Spring framework. • The IOC container takes responsibility for object instantiation, it can also support important creational patterns such as singletons, prototypes, and object pools. Copyright(c) Oded Nissan 2010
  • 25. Aspect Oriented Programming Framework • AOP enables us to capture the cross-cutting code in modules such as interceptors that can be applied declaratively wherever the concern they express applies — without imposing tradeoffs on the objects benefiting from the services. • Spring AOP allows the proxying of interfaces or classes. It provides an extensible pointcut model, enabling identification of which sets of method to advise Copyright(c) Oded Nissan 2010
  • 26. Data access Abstraction. • Spring provides an abstraction layer over JDBC that is significantly simpler and less error-prone to use than JDBC when you need to use SQLbased access to relational databases. • The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, Hibernate and JDO. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously. Copyright(c) Oded Nissan 2010
  • 27. Data access Abstraction. • Spring provides support for sending and receiving JMS messages in a much simpler way than provided through standard JEE. • JMX support: Spring supports JMX management of application objects it configures. • The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. Copyright(c) Oded Nissan 2010
  • 28. Transaction management. • Spring supports one of the key features of the EJB model- declarative transactions: – With declarative transaction management, the transactional behavior of beans is managed by the container. – Declarative transaction management reduces the complexity of transactions for application developers and makes it easier to create robust transactional applications. Copyright(c) Oded Nissan 2010
  • 29. Transaction management • Spring supports Declarative Transaction management through the use of AOP. • Spring’s transaction module can work with JTA transactions or local transactions using JDBC, JPA, Hibernate or JDO by simply adjusting the configuration files. Copyright(c) Oded Nissan 2010
  • 30. MVC Web Framework. • Spring provides a web framework based on the Model-View-Controller (MVC) paradigm. • Spring MVC provides out-of-the-box implementations of workflow typical to web applications. It is highly flexible, allowing you to use a variety of different view technologies. It also enables you to fully integrate with your Spring-based, middle-tier logic through the use of the Dependency Injection Copyright(c) Oded Nissan 2010
  • 31. The MVC Pattern • • • The Model View Controller pattern provides a clean separation between the presentation logic and business logic. The MVC pattern is the foundation of most web frameworks. Can be implemented by mixing Servlets JSPs and Java Beans. Copyright(c) Oded Nissan 2010
  • 32. The MVC Pattern Copyright(c) Oded Nissan 2010
  • 33. The MVC Pattern • • • • The view part of the MVC pattern is usually implemented using a JSP page. A Java Bean represents the model part. The controller is represented by a Servlet. Business logic is implemented by Java classes or EJBs that are invoked by the controller servlet. Copyright(c) Oded Nissan 2010
  • 34. Integration • Spring supplies integration with various JEE technologies: – Web Services – EJB – JCA – JMX • Remoting framework over HTTP. • Task Execution and Scheduling. Copyright(c) Oded Nissan 2010
  • 35. Summary • What did we discuss ? – Spring Introduction – Spring Architecture – The Spring Framework Components Copyright(c) Oded Nissan 2010
  • 37. Dependency Injection and the IOC Container Copyright(c) Oded Nissan 2010
  • 38. Dependency Injection and the IOC Container • • • • • What is dependency injection? IOC container overview Working with Spring beans Managing dependencies Advanced features Copyright(c) Oded Nissan 2010
  • 39. What is dependency injection? • Dependency Injection is a form of push configuration; the container "pushes" dependencies into application objects at runtime. • This is the opposite of traditional pull configuration, in which the application object "pulls" dependencies from its environment. Copyright(c) Oded Nissan 2010
  • 40. What is dependency injection? • Also called Inversion of control and the Hollywood pattern (“Don’t call me I’ll call you”). • Dependency injection can be implemented with or without a framework. • The framework simplifies and automates the injection of dependencies. Copyright(c) Oded Nissan 2010
  • 41. What is dependency injection? An example and discussion. • Copyright(c) Oded Nissan 2010
  • 42. Advantages of Dependency Injection • Application classes are self-documenting, and dependencies are explicit • No lock-in to a particular framework, or proprietary code. • Greater flexibility in managing configurations. • Code focuses on application logic, rather than dependency management or infrastructure. • Unit testing is easier. Copyright(c) Oded Nissan 2010
  • 43. Dependency Injection Frameworks • Some frameworks deal only with dependency injections. Some of the popular dependency injection frameworks (besides Spring): – Google Guice. – Pico Container – JMock – JEE 5 and JEE 6 provide limited dependency injection. Copyright(c) Oded Nissan 2010
  • 44. IOC Container Overview • The IoC container and is responsible for instantiating, configuring, and assembling beans. • It gets its instructions on which objects to instantiate, configure, and assemble by reading configuration metadata. • The configuration metadata is represented in XML, Java annotations, or Java code. Copyright(c) Oded Nissan 2010
  • 45. IOC Container Overview • The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. • ApplicationContext is a sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext for use in web applications. • Usually we will work with the Applicationcontext. Copyright(c) Oded Nissan 2010
  • 47. IOC Container Overview The following is an example of a Spring XML configuration file: Each Bean has an id and a class attribute. The id attribute is a string that you use to identify the individual bean definition. The class attribute defines the type of the bean and uses the fully qualified classname. Copyright(c) Oded Nissan 2010
  • 48. Instantiating a Container • The container can be instantiated with an XML file that can be either on a specific file system path,URL or the classpath. • We will usually prefer the classpath mechanism. Copyright(c) Oded Nissan 2010
  • 50. IOC Container Configuration • Besides using several configuration files for the same container, configuration files can be included in other configuration files using the “import” tag: Copyright(c) Oded Nissan 2010
  • 51. Working with Beans • Use the getBean() method on the container to retrieve beans. • You can also supply the class as a parameter and avoid the cast on the returned object: Copyright(c) Oded Nissan 2010
  • 52. Instantiating Beans • To instantiate a bean, initialize the IOC container and call the getBean() method of the container to retrieve the bean: Copyright(c) Oded Nissan 2010
  • 53. Working with Beans • Spring beans have the following properties: – – – – – – – – – – – id name class scope constructor args properties autowire mode init-method destroy-method lazy initialization dependency check Copyright(c) Oded Nissan 2010
  • 54. Working with Beans • Beans are be identified with the “id” or “name” attributes. • The “id” attribute is a real XML id, so it can be validated by the XML parser for uniqueness. • However there are some limitation on the valid characters in an XML id. In that case the “name” attribute is an alternative. • The “id” tag is the preferred way of identifying beans. Copyright(c) Oded Nissan 2010
  • 55. Using a Factory • Beans can also be instantiated using a factory. • You can define a bean with a static factory method. Use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method. • Instantiation with an instance factory method invokes a non-static method of an existing bean from the container to create a new bean. Copyright(c) Oded Nissan 2010
  • 56. Using a Factory • Using a static factory: • Using an instance factory: Copyright(c) Oded Nissan 2010
  • 57. Working with Beans • Dependency injection comes with two flavors: – Setter based dependency injection- dependencies are injected using setter methods. – Constructor based dependency injection – dependencies are injected as parameters to the bean constructor. – We will usually prefer to use setter based dependency injection, since it is easier to maintain. Copyright(c) Oded Nissan 2010
  • 58. Setter based Dependency injection • Initializing a bean using XML: • Retrieving the bean: Copyright(c) Oded Nissan 2010
  • 59. Setter based Dependency injection • The bean class includes the appropriate getters and setters for the properties: Copyright(c) Oded Nissan 2010
  • 60. Constructor based Dependency Injection • The argument is supplied to the constructor in the XML file. The appropriate constructor is defined in the bean: Copyright(c) Oded Nissan 2010
  • 61. Constructor based Dependency Injection • Sometimes it is necessary to specify the argument types to prevent ambiguity. • If a bean has two constructors, one accepting a String and the other accepting an int, the container might not recognize which constructor we want to invoke. • The values specified as arguments or properties are converted from a string type to the correct type in the bean using Spring PropertyEditors. Copyright(c) Oded Nissan 2010
  • 62. Constructor based Dependency Injection • For example, see the constructors of SampleBean: • And the XML definition: Copyright(c) Oded Nissan 2010
  • 63. Constructor based Dependency Injection • In this case we need to specify the argument type to the container to prevent ambiguity: • We can also specify the argument position when the constructor has multiple arguments: Copyright(c) Oded Nissan 2010
  • 64. Dependency Injection • Spring’s dependency injection framework allows injecting the following types: – Primitive values – References to other beans – Collections Copyright(c) Oded Nissan 2010
  • 65. Dependency Injection • Injecting beans using method injection: Copyright(c) Oded Nissan 2010
  • 66. Dependency Injection • Injecting beans using constructor injection: Copyright(c) Oded Nissan 2010
  • 67. Collections Dependency Injection • You can use the <list>, <map> and <props> to inject collections into beans. Copyright(c) Oded Nissan 2010
  • 68. Collections Dependency Injection • As of Spring 2.0, the container supports the merging of collections. An application developer can define a parent-style <list/>, <map/>, <set/> or <props/> element, and have child-style <list/>, <map/>, <set/> or <props/> elements inherit and override values from the parent collection. • The child collection's values are the result of merging the elements of the parent and child collections, with the child's collection elements overriding values specified in the parent collection. Copyright(c) Oded Nissan 2010
  • 69. Collections Dependency Injection • Collections Merging: Copyright(c) Oded Nissan 2010
  • 71. Injecting Empty Values • Spring can inject empty values using an empty string or a <null> element: Copyright(c) Oded Nissan 2010
  • 72. Aliasing Beans • You can provide an alias name for an existing bean. • This is useful in case we need to use beans that exist in a different subsystem. • The bean is mapped from the name to the alias: Copyright(c) Oded Nissan 2010
  • 73. Using idref • The <idref> tag is used to reference other beans. It is an alternative to the <ref> tag. • The referenced bean name should be passed in the <idref> tag. This allows the container to verify the dependencies at deploy time, rather than at runtime. Copyright(c) Oded Nissan 2010
  • 74. Inner Beans • A <bean/> element inside the <property/> or <constructor-arg/> elements defines a socalled inner bean. • An inner bean is anonymous and is always of prototype scope. Copyright(c) Oded Nissan 2010
  • 75. Depends On • Sometimes there is a dependency between beans that is indirect. For example, when one bean depends on another bean being initialized before its creation. • This dependency management is achieved by using the <depends-on> tag that can explicitly force one or more beans to be initialized before the bean using this element is initialized. Copyright(c) Oded Nissan 2010
  • 76. Depends On • The <depends-on> tag can also specify several dependencies separated by commas. Copyright(c) Oded Nissan 2010
  • 77. Lazy Initialization • Lazy initialization is used when we want to load bean properties on demand as they are accessed by the program. • This is usually used when initialization is a costly operation. • Spring supports lazy initialization of beans by using the “lazy-init=true” attribute of the <bean> element. Copyright(c) Oded Nissan 2010
  • 78. Autowiring • Spring is able to use introspection of bean classes in the factory and perform autowiring of dependencies. • In autowiring, you leave the bean property or constructor argument undeclared (in the XML file), and Spring will use reflection to find the type and name of the property, and then match it to another bean in the factory based on type or name. Copyright(c) Oded Nissan 2010
  • 79. Autowiring • Autowiring at the bean level is controlled via the use of the autowire attribute, which has five possible values: – No – no autowiring Bean properties and constructor arguments must be explicitly declared. – byName- Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. – byType- Autowire by matching type. if there is exactly one bean in the factory of the same type as the property, the property value is set as that other bean. If there is more than one bean in the factory matching the type, it is considered a fatal error and an exception is raised. Copyright(c) Oded Nissan 2010
  • 80. Autowiring – constructor - Autowire the constructor by type. This works in essentially identical fashion to how byType works for properties, except that there must be exactly one matching bean, by type, in the factory for each constructor argument. – autodetect - Choose byType or constructor as appropriate. The bean is introspected, and if there is a default no-arg constructor, byType is used, otherwise, constructor is used. Copyright(c) Oded Nissan 2010
  • 82. Autowiring Limitations • Explicit dependencies in property and constructor-arg settings always override autowiring. • You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation is by-design. Copyright(c) Oded Nissan 2010
  • 83. Autowiring • Pros: – Less Spring configuration. – Configuration can be outdated. Autowiring will ensure that dependencies are up to date. • Cons: – Autowiring is less exact than explicit wiring. – Wiring information may not be available to tools that may generate documentation from a Spring container. – Does not provide the dependency documentation that explicit wiring does. Copyright(c) Oded Nissan 2010
  • 84. Excluding a Bean from Autowiring • On a per-bean basis, you can exclude a bean from autowiring. In Spring's XML format, set the autowire-candidate attribute of the <bean/> element to false; the container makes that specific bean definition unavailable to the autowiring infrastructure. • You can also limit autowire candidates based on pattern-matching against bean names. The toplevel <beans/> element accepts one or more patterns within its default-autowire-candidates attribute. Copyright(c) Oded Nissan 2010
  • 86. Bean Scopes • When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe. • Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports five scopes, three of which are available only if you use a web-aware ApplicationContext. Copyright(c) Oded Nissan 2010
  • 87. Bean Scopes Bean Scop Description Singleton Only one bean is created per container Prototype A bean is created with each bean request from the container Request A bean is created for each HTTP request. Session A bean is created for each HTTPSession Global-session Similar to session and applies only in the context of portlet-based web applications Copyright(c) Oded Nissan 2010
  • 90. Singleton Beans with Prototype Dependencies • When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean. • Usually this is not what we want. We want to get a new prototype bean every time we request it from the singleton bean. Copyright(c) Oded Nissan 2010
  • 91. Singleton Beans with Prototype Dependencies • One solution to this problem of a prototype bean in a singleton bean is to get the bean directly from the container. • However, that would make the bean container-aware and would break our dependency injection framework. • We can solve the problem a Spring mechanism called method injection. Copyright(c) Oded Nissan 2010
  • 92. Method Injection • Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. • The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method. Copyright(c) Oded Nissan 2010
  • 93. Method Injection • We create the singleton bean, with the method that lookups the prototype bean as abstract. With the following signature: • We then specify the lookup method name in the bean definition. Copyright(c) Oded Nissan 2010
  • 95. Dependency Check • Sometimes we want to ensure that all properties are set on a bean. • The Spring IoC container can check for unresolved dependencies of a bean deployed into the container. • You can enable dependency checking per bean, just as with the autowiring functionality. • In XML-based configuration metadata, you specify dependency checking via the dependency-check attribute in a bean definition. Copyright(c) Oded Nissan 2010
  • 96. Dependency Check • The dependency-check attribute can have the following values: – none – no dependency check will be done. – simple – dependency check will be done for primitive types and collections. – object – dependency checking for other beans. – all – dependency checking for all bean properties. Copyright(c) Oded Nissan 2010
  • 97. Lifecycle Callbacks • Lifecycle callbacks allow you to interact with the spring container. • you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans. Copyright(c) Oded Nissan 2010
  • 98. Lifecycle Callbacks Example using callbacks: • Copyright(c) Oded Nissan 2010
  • 99. Lifecycle Callbacks • The problem with the former approach is that now our bean is dependent on spring specific interfaces. • An alternative is to specify the initialization and destroy callbacks in the spring configuration using the init-method and destroy-method bean attributes. Copyright(c) Oded Nissan 2010
  • 100. Lifecycle Callbacks Using init-method: • • Using destroy-method: Copyright(c) Oded Nissan 2010
  • 101. Lifecycle Callbacks • You can configure the Spring container to look for named initialization and destroy callback method names on every bean. • This means that you, as an application developer, can write your application classes and use an initialization callback called init() for each bean, without configuring it in the XML file. • This feature also enforces a consistent naming convention for initialization and destroy method callbacks. Copyright(c) Oded Nissan 2010
  • 102. Lifecycle Callbacks Example of default lifecycle callbacks: • Copyright(c) Oded Nissan 2010
  • 104. Container Shutdown Hook • In a non web environment you can also register a shutdown hook that will be called when the container is shutdown. • The shutdown hook will be called when the program’s main method exits: Copyright(c) Oded Nissan 2010
  • 105. Injecting a Spring Context • Sometimes we will need to access the spring context from outside the spring container. • Since we don’t want to create the ApplicationContext again, we want to inject the existing ApplicationContext into our class. • To inject the spring context we write a class that implements the ApplicationContextAware interface, define it as a spring bean and provide a static method to retrieve the context. Copyright(c) Oded Nissan 2010
  • 106. Injecting a Spring Context • Example of a helper class that the context will be injected to: Copyright(c) Oded Nissan 2010
  • 107. Bean Definition Inheritance • Sometimes we might want to inherit the bean definition in a child bean. • A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. • This is done by specifying the “parent” attribute in the child bean configuration. Copyright(c) Oded Nissan 2010
  • 108. Bean Definition Inheritance • Note that bean definition inheritance does not necessarily imply class inheritance. • We can use bean definition inheritance with or without class inheritance. • We can also use class inheritance with or without bean definition inheritance. Copyright(c) Oded Nissan 2010
  • 109. Bean Definition Inheritance • Bean definition inheritance example: Copyright(c) Oded Nissan 2010
  • 110. Externalizing Properties • You use the PropertyPlaceholderConfigurer to externalize property values from a bean definition into another separate file in the standard Java Properties format. • Doing so enables the person deploying an application to customize environment-specific properties such as database URLs and passwords, without the complexity or risk of modifying the main XML definition file or files for the container. Copyright(c) Oded Nissan 2010
  • 111. Externalizing Properties • This mechanism is called the PropertyPlaceholderConfigurator. To use it: – Specify placeholders for externalized properties in the bean definition: Copyright(c) Oded Nissan 2010
  • 112. Externalizing Properties – Define the properties to be replaced and their replace values in a properties file: – Use the configuration to have the context load the properties file: Copyright(c) Oded Nissan 2010
  • 114. Internationalization • The ApplicationContext interface extends an interface called MessageSource, to provide internationalization (i18n) functionality. • Spring also provides the interface HierarchicalMessageSource, which can resolve messages hierarchically. • The basic method to retrieve message is: – String getMessage(String code, Object[] args, String default, Locale loc) • When no message is found for the specified locale, the default message is used. • Additional flavors of the getMessage method are available. Copyright(c) Oded Nissan 2010
  • 115. Internationalization • When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. • The bean must have the name messageSource. If such a bean is found, all calls to the preceding methods are delegated to the message source. • If no message source is found, the ApplicationContext attempts to find a parent containing a bean with the same name. If it does, it uses that bean as the MessageSource. • If the ApplicationContext cannot find any source for messages, an empty DelegatingMessageSource is instantiated in order to be able to accept calls to the methods defined above. Copyright(c) Oded Nissan 2010
  • 116. Internationalization • Spring provides two MessageSource implementations, ResourceBundleMessageSource and StaticMessageSource. Both implement HierarchicalMessageSource. • ResourceBundleMessageSource example: Copyright(c) Oded Nissan 2010
  • 117. Internationalization • The example assumes we have three different resource bundles called format, exceptions and windows. • Spring's various MessageResource implementations follow the same locale resolution and fallback rules as the standard JDK ResourceBundle. • The locale is appended to the file name, the suffix is “properties”. Copyright(c) Oded Nissan 2010
  • 118. Internationalization • For example, messages for the hebrew locale will be stored in a files called format_he.properties. • The country code can also be appended for example: format_he_IL.properties. • The default locale is named format.properties. • We need to specify the locale so when retrieving the message. Copyright(c) Oded Nissan 2010
  • 119. Internationalization Bundle files: • • Retrieving the messages using the ApplicationContext (Note that ApplicationContext also implements MessageSource): Copyright(c) Oded Nissan 2010
  • 120. Summary • What did we discuss ? – What is dependency injection? – IOC container overview – Working with Spring beans – Managing dependencies – Advanced features Copyright(c) Oded Nissan 2010
  • 123. Resources • • • • • Available Resource implementations The Resource Loader Injecting Resources ApplicationContext and Resources Resources and Wildcards Copyright(c) Oded Nissan 2010
  • 124. Resources • Spring contains various resource implementations that support retrieving resources from difference sources. • The possible sources include the filesystem, the classpath, URLs and the ServletContext. • All resource implementations implement the Resource interface. Copyright(c) Oded Nissan 2010
  • 125. Resources • The Resource Interface: Copyright(c) Oded Nissan 2010
  • 126. Resources • The following resource implementations are supported by Spring: – URLResource – ClassPathResource – FileSystemResource – ServletContextResource – InputStreamResource – ByteArrayResource Copyright(c) Oded Nissan 2010
  • 127. Resources • Resources are loaded by a ResourceLoader, there are various implementations of the ResourceLoader interface that support loading different resources. • All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances. Copyright(c) Oded Nissan 2010
  • 128. Resources • When you call getResource() on a specific application context, and the location path specified doesn't have a specific prefix, you will get back a Resource type that is appropriate to that particular application context. For example this would return a ClassPathResource : Copyright(c) Oded Nissan 2010
  • 129. Resources • You can also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix: • Or a url prefix or file prefix: Copyright(c) Oded Nissan 2010
  • 130. Injecting Resources • Resources can also be injected to beans using dependency injection. When the property is of a resource type the values will be used to initialize the appropriate resource. In the following examples the appropriate resource type will be initialized: Copyright(c) Oded Nissan 2010
  • 131. Application Contexts and Resources • The constructor of an ApplicationContext takes a path String as a parameter and uses the appropriate resource loader for the specific ApplicationContext implementation used. For example: Copyright(c) Oded Nissan 2010
  • 132. Resources and Wildcards • Resource paths may contain the special "classpath*:" prefix and/or internal Ant-style regular expressions. • One use for this mechanism is when doing component-style application assembly. All components can 'publish' context definition fragments to a well-known location path, and all of them will be picked up by the applicationcontext using wildcards. Copyright(c) Oded Nissan 2010
  • 133. Resources and Wildcards • Ant style regular expression examples: • In this example all resources matching the regular expressions will be loaded. Copyright(c) Oded Nissan 2010
  • 134. Resources and Wildcards • Using the classpath*: prefix : • In this example all resources found in the classpath with the “conf/appContext.xml” path will be loaded. Copyright(c) Oded Nissan 2010
  • 136. Summary • What did we discuss ? – Available Resource implementations – The Resource Loader – Injecting Resources – ApplicationContext and Resources – Resources and Wildcards Copyright(c) Oded Nissan 2010
  • 139. Spring AOP • • • • • What is AOP ? AOP Concepts Spring AOP options Example Summary Copyright(c) Oded Nissan 2010
  • 140. What is AOP ? • Aspect-Oriented Programming (AOP) is an important technology, well-suited to solving many common problems. Spring offers AOP features to complement its IoC features and ensure that enterprise service code does not pollute your application objects. • Spring takes a pragmatic approach to AOP. You can use as little AOP as you want, or integrate with AspectJ to harness the power of AOP extensions to the Java language. Copyright(c) Oded Nissan 2010
  • 141. AOP Concepts • Aspect: a modularization of a concern that cuts across multiple classes. • Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. • Advice: action taken by an aspect at a particular join point. • Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut Copyright(c) Oded Nissan 2010
  • 142. AOP Concepts • Introduction- declaring additional methods or fields on behalf of a type. • Target object- object being advised by one or more aspects. • AOP proxy- an object created by the AOP framework in order to implement the aspect contracts. • Weaving - linking aspects with other application types or objects to create an advised object. Copyright(c) Oded Nissan 2010
  • 143. Advice Types • Before advice- Advice that executes before a join point. • After returning advice- Advice to be executed after a join point completes normally. • After throwing advice- Advice to be executed if a method exits by throwing an exception. • After (finally) advice- Advice to be executed regardless of the means by which a join point exits. • Around advice- Advice that surrounds a join point such as a method invocation. Copyright(c) Oded Nissan 2010
  • 144. Spring AOP • Spring AOP is implemented in pure Java. There is no need for a special compilation process. • One of the central tenets of the Spring Framework is that of non-invasiveness; this is the idea that you should not be forced to introduce framework-specific classes and interfaces into your business/domain model. Copyright(c) Oded Nissan 2010
  • 145. AOP Proxies • Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies. This enables any interface to be proxied. • Spring AOP can also use CGLIB proxies. This is necessary to proxy classes, rather than interfaces. CGLIB is used by default if a business object does not implement an interface. Copyright(c) Oded Nissan 2010
  • 146. AOP Proxies • When using dynamic proxies, a proxy object is generated on the fly for the proxied object. The proxy object then intercepts the method calls on the real object. • The proxy can then advices on the object and also invoke the real method on the real object. Copyright(c) Oded Nissan 2010
  • 147. AOP Proxies • Spring provides an API to programmatically apply dynamic proxies to objects. • Here we can see the “foo” method intercepted by the proxy: Copyright(c) Oded Nissan 2010
  • 148. Spring AOP • There are currently 3 options for using Spring AOP: – @AspectJ style annotations. – Schema based AOP support – Old Spring AOP APIs (prior to version 2.0) Copyright(c) Oded Nissan 2010
  • 149. @AspectJ Support • @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. • Spring 2.0 interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching. • The AOP runtime is still pure Spring AOP though, and there is no dependency on the AspectJ compiler or weaver. Copyright(c) Oded Nissan 2010
  • 150. Schema based AOP Support • Spring also offers support for defining aspects using the new "aop" namespace tags. • The exact same pointcut expressions and advice kinds are supported as when using the @AspectJ style. • Definitions will be done in XML rather than in annotations. Copyright(c) Oded Nissan 2010
  • 151. AspectJ@ vs. schema based AOP • XML can be used with any Java version. • XML can be changed without changing and compiling code. • AspectJ@ annotations unite the code with the configuration. • The @AspectJ style supports additional instantiation models, and richer pointcut composition. • We will discuss only schema based AOP. Copyright(c) Oded Nissan 2010
  • 152. Using AOP • To use Spring AOP: – Write a bean with your advice methods. – Declare the bean to be an aspect. – Specify the pointcut to which the aspect will be applied in the configuration file. – Specify the advice to be applied to the pointcut in the configuration file. Copyright(c) Oded Nissan 2010
  • 153. Spring AOP Pointcut expressions • execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP) • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type Copyright(c) Oded Nissan 2010
  • 154. Spring AOP Pointcut expressions • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types • @target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type • @args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s) • @within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP) • @annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation Copyright(c) Oded Nissan 2010
  • 155. AOP Pointcut Expressions • Execution of any public method. • Execution of any method in the AccountService interface. • Execution of any method in the service package. • Execution of any method in the service package or any of its subpackages Copyright(c) Oded Nissan 2010
  • 156. AOP Pointcut Expressions • Any joinpoint within the service package. • Any join point where the proxy implements the AccountService interface. • Any join point where the target object implements the AccountService interface. • Any join point with a single parameter of type Serializable. Copyright(c) Oded Nissan 2010
  • 157. Spring AOP Example • We want to profile a method execution by measuring the time it takes to execute the method. • We define the SimpleProfiler class as an aspect. • We apply an around advice to the getFoo method in theFooService interface. Copyright(c) Oded Nissan 2010
  • 158. Spring AOP Example • We define a FooService interface and implement it. Copyright(c) Oded Nissan 2010
  • 159. Spring AOP Example • We write the SimpleProfiler class which will serve as the aspect. We write the profile method as an around advice. Copyright(c) Oded Nissan 2010
  • 160. Spring AOP Example • We use XML configuration to apply the advice of the SimpleProfiler aspect to the FooService interface. Copyright(c) Oded Nissan 2010
  • 161. Spring AOP Example • The following is a test driver invoking the bean the aspect was applied on and the resulting output. Copyright(c) Oded Nissan 2010
  • 163. Spring Best Practices • • • • Prefer setter based injection. Use naming conventions for beans. Try to avoid using autowiring. Carefully check the need for prototype scope beans. • Reuse bean definitions when possible. • Use AOP carefully. • Not every class is a Spring bean Copyright(c) Oded Nissan 2010
  • 164. Summary • What did we discuss ? – What is AOP ? – AOP Concepts – Spring AOP options – Example Copyright(c) Oded Nissan 2010