Spring Dependencies
An application will have certain
objects that work together to present what the end-user sees as a coherent
application. We can define a number of bean definitions that are stand-alone,
each to themselves, to a fully realized application where objects work (or
collaborate) together to achieve some goal.
Injecting Dependencies
It becomes evident upon usage that
code gets much cleaner when the DI principle is applied, and reaching a higher
grade of decoupling is much easier when beans do not look up their
dependencies, but are provided with them.
Setter Injection
Setter-based DI is realized by
calling setter methods on your beans after invoking a no-argument constructor
or no-argument static factory method to instantiate your bean.
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;
}
}
|
Constructor Injection
Constructor-based DI is realized by
invoking a constructor with a number of arguments, each representing a
collaborator. Additionally, calling a static factory method can be considered
almost equivalent.
public
class SimpleMovieLister {
// the SimpleMovieLister has a dependency
on the MovieFinder
private MovieFinder movieFinder;
// a constructor so that the Spring
container can 'inject' a MovieFinder
public SimpleMovieLister
(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
|
Constructor or Setter DI?
·
Setter
based DI makes objects of that class responsive to being re-configured (or re-injected)
at some later time.
·
Constructor-injection
supplying all of an object's dependencies means that that object is never
returned to client (calling) code in a less than totally initialized state.
No comments:
Post a Comment