9. DI / IoC
Brief history about DI
Dependency Inversion: Precursor to Dependency Injection
What is DI?
DI Vs IOC
Types of IOC
Dependency Pull
Contextualized Dependency Lookup (CDL)
Types of DI
Constructor
Setter
9
11. Types of IOC [Contd.]
2. Contextualized Dependency Lookup
public class ContextualizedDependencyLookup
implements ManagedComponent {
private Dependency dep;
public void performLookup(Container container)
{
this.dep = (Dependency)container.get
Dependency("myDependency");
}
}
11
12. Types of DI
1. Constructor Dependency
public class ConstructorInjection {
private Dependency dep;
public ConstructorInjection(Dependency dep) {
this.dep = dep;
}
}
12
13. Types of IOC [Contd.]
2. Setter Dependency
public class SetterInjection {
private Dependency dep;
public void setMyDependency(Dependency dep) {
this.dep = dep;
}
}
13
14. Injection Vs Lookup
Disadvantages of Lookup
Need to obtain handler of Registry to interact
Classes are dependent on classes & interfaces of IOC container
Testing in isolation from container becomes difficult
Advantages of Injection
Minimal impact on existing code
Classes are completely decoupled from IOC container
Testing becomes much more easier
14
16. Dependency Injection with Spring
Hello World example - [HelloWorldMainApp]
Beans & Bean Factories –
Setter DI example –
[SetterDependencyInjectionMainApp]
Constructor DI example – [Main]
Constructor confusion example – [ConstructorConfusionDemo]
16
22. Bean Instantiation Modes [Contd.]
Non-Singleton Instantiation Modes
Mode Description
Prototype Every call to the getBean() method returns a new
instance of the bean.
request Every call to the getBean() method in a web
application will return a unique instance of the
bean for every HTTP request. This behavior is only
implemented in the WebApplicationContext and its
subinterfaces.
session Calls to the getBean() method will return a unique
instance of the bean for every HTTP Session. Just
like request, this scope is only available in
WebApplicationContext and its subinterfaces.
global The getBean() calls will return a unique instance of
session the bean for the global HTTP session in a portlet
context. Just like request and session scopes, this
instantiation mode is only supported in
WebApplicationContext and its subinterfaces. 22
23. Bean Instantiation Modes [Contd.]
Choosing an instantiation mode
Singleton
Shared objects with no state
Shared objects with read only state
Shared objects with shared state
High throughput objects with writable state
Non-Singleton
Objects with writable state
Objects with private state
Bean scope example – [ScopeDemo]
23
25. Auto wiring your Beans
Spring supports 4 modes of auto wiring
byName
byType
Constructor
Autodetect
Auto wiring example – [AutowiringDemo]
When to use
25
26. Checking Dependencies
Spring has 3 modes for dependency checking
simple
object
all
Example
<bean id="simpleBean1"
class="com.innotech.spring.training.SimpleBean“
dependency-check="simple">
26
29. Life Cycle of Spring Bean [Contd.]
BeanFactoryPostProcessor
Executes after spring has finished constructing BeanFactory but
before BeanFactory constructs beans
BeanFactoryPost-Processors of Spring
Post- Description
Processors
AspectJWeavingE This post-processor registers AspectJ’s
nabler ClassPreProcessorAgentAdapter to be used in
Spring’s LoadTimeWeaver
CustomAutowire This one allows you to specify annotations, in
Configurer addition to @Qualifier, to indicate that a bean is a
candidate for automatic wiring.
CustomEditorCon This registers the PropertyEditor implementations
figurer that Spring will use in attempts to convert string
values in the configuration files to types required
by the beans.
29
30. Life Cycle of Spring Bean [Contd.]
BeanFactoryPost-Processors of Spring
Post- Description
Processors
CustomScop Use this post-processor to configure custom scopes (in
eConfigurer addition to singleton, prototype, request, session, and
globalSession) in the configuration file. Set the scopes
property to a Map containing the scope name as key
and the implementation of the Scope interface as value.
PreferencesP This post-processor will replace the values in beans'
laceholderCo properties using JDK 1.4’s Preferences API. The
nfigurer Preferences API states that it will try to resolve a value
first from user preferences (Preferences.userRoot()),
then system preferences (Preferences.systemRoot()),
and finally from a preferences file.
PropertyPlac This post-processor will replace values of properties
eholderConfi with values loaded from the configured properties file, if
gurer the values follow certain formatting rules (by default, $
{property-name}). 30
31. Life Cycle of Spring Bean [Contd.]
BeanFactoryPost-Processors of Spring
Post- Description
Processors
PropertyOverr This post-processor will replace values of beans’
ideConfigurer properties from values loaded from the specified
properties file. It will search the properties file for a
property constructed from the bean name and
property: for property a of bean x, it will look for x.a in
the properties file. If the property does not exist, the
post-processor will leave the value found in the
configuration file.
ServletContex This post-processor extends
tPropertyPlac PropertyPlaceholderConfigurer; therefore, it replaces
eholderConfig beans’ properties if they follow the specified naming
urer convention. In addition to its superclass, this processor
will load values from context-param entries of the
servlet that is hosting the application.
31
32. Life Cycle of Spring Bean [Contd.]
BeanPostProcessor of Spring has 2 methods
postProcessBeforeInitialization
postProcessAfterInitialization
Spring Life Cycle example – [LifeCycleDemo,
SimpleBeanDemo]
32
33. Spring’s ApplicationContext
Its an interface same as BeanFactory
ApplicationContext Vs BeanFactory
Implementation of ApplicationContext
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
XmlWebApplicationContext
33
34. Spring’s built-in Property Editors
Property Editor Reg. by Description
Default
ByteArrayPropert Y This PropertyEditor converts a String value
yEditor into an array of bytes.
ClassEditor Y The ClassEditor converts from a fully
qualified class name into a Class instance.
When using this PropertyEditor, be careful
not to include any extraneous spaces on
either side of the class name when using
XmlBeanFactory, because this results in a
ClassNotFoundException.
CustomBooleanEd N This customizable editor for Boolean values
itor is intended to be used in UI-centric code,
where it can parse different String
representations of Boolean values; for
example, “Yes”/ “No” or “Ano”/“Ne”.
34
35. Spring’s built-in Property Editors [Contd.]
Property Reg. by Description
Editor Default
CustomCollecti N This PropertyEditor can be used to create any
onEditor type of the Java Collections framework or an
array.
CustomDateEd N Just like the CustomBooleanEditor, this
itor PropertyEditor is typically used in the
controller’s initBinder method to enable the
application to parse dates entered in a
localespecific format to a java.util.Date.
FileEditor Y The FileEditor converts a String file path into a
File instance. Spring does not check to see if
the file (or directory) exists.
CustomNumbe N This PropertyEditor converts a String into an
rEditor Integer, a Long, a BigDecimal, or any other
Number subclass.
35
36. Spring’s built-in Property Editors [Contd.]
Property Reg. by Description
Editor Default
LocaleEditor Y The LocaleEditor converts the String
representation of a locale, such as en-GB, into
a java.util.Locale instance.
PatternEditor Y This ResourceEditor converts a regular
expression (passed in as a String) into a
java.util.regex.Pattern instance.
StringTrimme N The StringTrimmerEditor can be used to trim
rEditor nonempty Strings and to transform each
empty String into null.
InputStreamE Y This editor will convert a String into an
ditor InputStream. Note that this PropertyEditor is a
not reflective; it can only convert String to
InputStream, not the other way around.
Internally, the conversion is achieved by
instantiating a temporary ResourceEditor for a
Resource. 36
37. Spring’s built-in Property Editors [Contd.]
Property Reg. by Description
Editor Default
PropertiesEdit Y PropertiesEditor converts a String in the
or format key1=value1n key2=value2n
keyn=valuen into an instance of java.util.
Properties with the corresponding properties
configured.
StringArrayPr Y The StringArrayPropertyEditor class converts a
opertyEditor comma-separated list of String elements into a
String array.
URLEditor N The URLEditor converts a String representation
of a URL into an instance of java.net.URL.
37
41. Types of Advice
Advice Name Interface
Before org.springframework.aop.Meth
odBeforeAdvice
After Returning org.springframework.aop.After
ReturningAdvice
Around org.aopalliance.intercept.Metho
dInterceptor
Throws org.springframework.
aop.ThrowsAdvice
Introduction org.springframework.aop.
IntroductionInterceptor
41
42. The Pointcut Interface
public interface Pointcut {
ClassFilter getClassFilter ();
MethodMatcher getMethodMatcher();
}
public interface ClassFilter{
boolean matches(Class clazz);
}
public interface MethodMatcher{
boolean matches(Method m, Class targetClass);
boolean isRuntime();
boolean matches(Method m, Class targetClass,
Object[] args);
42
}
43. Types of Pointcut
Implementation Description
Class
org.springframewo The ComposablePointcut class is used to compose two
rk.aop.support.Co or more pointcuts together with operations such as
mposablePointcut union() and intersection().
org.springframewo The ControlFlowPointcut is a special case pointcut that
rk.aop.support.Co matches all methods within the control flow of
ntrolFlowPointcut another method, that is, any method that is invoked
either directly or indirectly as the result of another
method being invoked.
org.springframewo The JdkRexepMethodPointcut allows you to define
rk.aop.support.Jdk pointcuts using JDK 1.4 regular expression support.
RegexpMethodPoin This class requires JDK 1.4 or higher.
tcut
org.springframewo The AnnotationMatchingPointcut class is used for
rk.aop.Annotation creating Java 5 annotated pointcuts.
MatchingPointcut
43
44. Types of Pointcut [Contd.]
Implementation Description
Class
org.springframework Using the NameMatchMethodPointcut, you can
.aop.support.NameM create a pointcut that performs simple matching
atchMethodPointcut against a list of method names.
org.springframework The StaticMethodMatcherPointcut class is intended
.aop.StaticMethodM as a base for building static pointcuts.
atcherPointcut
org.springframework The DynamicMethodMatcherPointcut class is a
.aop.DynamicMetho convenient superclass for building dynamic
dMatcherPointcut pointcuts that are aware of method arguments at
runtime.
org.springframework The AspectJExpressionPointcut convenient class is
.aop.AspectJExpressi used for defining pointcuts using AspectJ expression
onPointcut language. Note that only method execution
pointcuts can be defined, as Spring AOP does not
support other AspectJ pointcuts in the current
version. 44
46. Concepts in Spring Data Access Support
Understanding Spring’s DataAccessException
You are not forced to handle DataAccessException
Spring classifies exception for you
46
47. Concepts in Spring Data Access Support [Contd.]
Exception Description
CleanupFailureDataA An operation completes successfully, but an
ccessException exception occurs while cleaning up database
resources (e.g., closing a Connection).
DataAccessResource A data access resource fails completely, such as not
FailureException being able to connect to a database.
DataIntegrityViolatio An insert or update results in an integrity violation,
nException such as a violation of a unique constraint.
DataRetrievalFailure Certain data could not be retrieved, such as not
Exception finding a row by primary key.
DeadlockLoserDataA The current process was a deadlock loser.
ccessException
IncorrectUpdateSem When something unintended happens on an update,
anticsData- such as updating more rows than expected. When
AccessException this exception is thrown, the operation’s transaction
has not been rolled back.
47
48. Concepts in Spring Data Access Support [Contd.]
Exception Description
InvalidDataAccessAp A data access Java API is used incorrectly, such as
iUsageException failing to compile a query that must be compiled
before execution.
InvalidDataAccessRe A data access resource is used incorrectly, such as
sourceUsage using bad SQL grammar to access a relational
Exception database.
OptimisticLockingFai There is an optimistic locking failure. This will be
lureException thrown by ORM tools or by custom DAO
implementations.
TypeMismatchDataA There is a mismatch between Java type and data
ccessException type, such as trying to insert a String into a
numeric database column.
UncategorizedDataA Something goes wrong, but a more specific
ccessException exception cannot be determined.
48
53. Spring Transaction
What is TRANSACTION?
Types of Transaction
Local Transaction
Global Transaction
Properties of Transaction
Atomicity
Consistency
Isolation
Durability
53
54. TransactionDefinition interface
public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
int getTimeout();
boolean isReadOnly();
}
54
55. Spring’s Transaction Isolation levels
Isolation Level Description
ISOLATION_DEF Use the default isolation level of the underlying data-
AULT store.
ISOLATION_REA Allows you to read changes that have not yet been
D_UNCOMMITTE committed. May result in dirty reads, phantom reads,
D and non-repeatable reads.
ISOLATION_REA Allows reads from concurrent transactions that have
D_COMMITTED been committed. Dirty reads are prevented, but
phantom and non-repeatable reads may still occur.
ISOLATION_REP Multiple reads of the same field will yield the same
EATABLE_READ results, unless changed by the transaction itself. Dirty
reads and non-repeatable reads are prevented by
phantom reads may still occur.
ISOLATION_SERI This fully ACID-compliant isolation level ensures that
ALIZABLE dirty reads, non-repeatable reads, and phantom reads
are all prevented. This is the slowest of all isolation
levels because it is typically accomplished by doing full
table locks on the tables involved in the transaction.
55
56. Spring’s Transaction Propagation Behavior
Propagation What does it mean
Behavior
PROPAGATION Spring will use an active transaction if it exists. If
_REQUIRED not, Spring will begin a new transaction.
PROPAGATION Spring will use an active transaction; if there is
_SUPPORTS no active transaction, Spring will not start a new
one.
PROPAGATION Spring will use an active transaction; if there is
_MANDATORY no active transaction, Spring will throw an
exception.
PROPAGATION Spring will always start a new transaction. If an
_REQUIRES_N active transaction already exists, it is suspended.
EW
56
57. Spring’s Transaction Propagation Behavior [Contd.]
Propagation What does it mean
Behavior
PROPAGATION Spring will not execute the code in an active
_NOT_SUPPOR transaction. The code always executes non-
TED transactionally and suspends any existing
transaction.
PROPAGATION This always executes nontransactionally even if
_NEVER an active transaction exists. It throws an
exception if an active transaction exists.
PROPAGATION This runs in a nested transaction if an active
_NESTED Transaction exists. If there is no active
transaction, the code runs as if
TransactionDefinition.PROPAGATION_REQUIRED
is set.
57
58. Left overs’ !
Spring - Hibernate
Spring - Webservice
Spring schedulers
Spring email
Spring MVC
Spring – UnitTesting/TDD
....
...
..
List goes on & on . . . :D
58
60. Resources/References
Spring – www.springframework.org
Inversion of Control -
http://www.martinfowler.com/articles/injection.html
Spring in Action – Walls, Breidenbach
60
61. Personal Information
E-mail : shah_d_p@yahoo.com
: http://twitter.com/dhaval201279
: http://in.linkedin.com/in/dhavalshah201279
61
Editor's Notes
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based
Spring MVC – a single shared controller instance handles a particular request type - controllers, interceptors run in the IoC container - allows multiple DispatcherServlets that can share an “application context” - Interface based not class-based