These are patterns to achieve loose coupling in java
programming
DI(Dependency
Injection):
Dependency injection is a pattern used to create
instances of objects
that other objects rely upon without knowing at compile
time
which class will be used to provide that functionality or simply the way
of injecting properties to an object is called dependency
injection.
We have three types of
Dependency
injection
- Constructor
Injection - Setter/Getter Injection
- Interface
Injection
Spring will
support only Constructor Injection and Setter/Getter Injection.
IOC(Inversion Of
Control):
Giving control to the container to create and inject
instances of objects that your application depend upon, means instead of you are
creating an object using the new
operator, let the container do
that for you.
Inversion of control relies on dependency injection because a
mechanism is needed in order to activate the components providing the specific
functionality
The two concepts work together in
this way to allow for much more flexible, reusable, and encapsulated code to be written.
As such, they are important concepts in designing object-oriented
solutions.
Example for Dependency
injection
Previously we are
writing code like
this
Public
MyClass{
DependentClass dependentObject
/*
At somewhere
in our code we need to instantiate
the object with new operator inorder to
use it or perform some method.
*/
dependentObject= new
DependentClass();
dependentObject.someMethod();
}
With
Dependency injection, the dependency injector will take off the instantiation for us
Public MyClass{
/*
Dependency injector will instantiate object*/
DependentClass
dependentObject
/*
At somewhere in our code we perform
some method.
The process of instantiation will be handled by the dependency
injector
*/
dependentObject.someMethod();
}
The
above process of giving the control to some other (for example the container) for the
instantiation and injection can be termed as Inversion of
Control
You can read more on
dependency injection and IOC in my answer :- You can find advantages and applications of
the concepts here.
href="https://stackoverflow.com/questions/130794/what-is-dependency-injection/47090662#47090662">What
is dependency injection?
No comments:
Post a Comment