Dependency
injection (DI) is a process whereby objects define their dependencies, that is,
the other objects they work with, only through constructor arguments, arguments
to a factory method, or properties that are set on the object instance after it
is constructed or returned from a factory method.
The container
then injects those dependencies when it creates the bean.
This
process is fundamentally the inverse, hence the name Inversion of Control
(IoC), of the bean itself controlling the instantiation or location of its
dependencies by using direct construction of classes, or a mechanism such as
the Service Locator pattern.
The
org.springframework.beans and org.springframework.context packages are the
basis for Spring Framework’s IoC container.
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.
In short,
the BeanFactory provides the configuration framework and basic functionality,
and the ApplicationContext adds more enterprise-specific functionality. The
ApplicationContext is a complete superset of the BeanFactory.
1. Constructor
Based Dependency Injection:-
Constructor-based
DI is accomplished by the container invoking a constructor with a number of
arguments, each representing a dependency. Calling a static factory method with
specific arguments to construct the bean is nearly equivalent, and this
discussion treats arguments to a constructor and to a static factory method
similarly.
Example:-
public class
SimpleMovieLister {
// the SimpleMovieLister has a dependency
on a MovieFinder
private MovieFinder movieFinder;
// a constructor so that the Spring
container can inject a MovieFinder
public SimpleMovieLister(MovieFinder
movieFinder) {
this.movieFinder = movieFinder;
}
// business logic that actually uses the
injected MovieFinder is omitted...
}
2. Setter Based
Dependency Injection:-
Setter-based
DI is accomplished by the container calling setter methods on your beans after
invoking a no-argument constructor or no-argument static factory method to
instantiate your bean.
Example:-
public class
SimpleMovieLister {
// the SimpleMovieLister has a dependency
on the MovieFinder
private MovieFinder movieFinder;
// a setter method so that the Spring
container can inject a MovieFinder
public void setMovieFinder(MovieFinder
movieFinder) {
this.movieFinder = movieFinder;
}
// business logic that actually uses the
injected MovieFinder is omitted...
}
[Spring Interview Questions]
We recommend you take Big Data Hadoop class room training at eMexo Technologies in electronic city, Bangalore to learn more about Big Data Hadoop.
0 Comments:
Post a Comment