Aggregation: If two objects have there own life cycle and not tightly coupled with each other(can exists independently).
Class A {
B b;
}
The default value for b
will be null
and A's
object can exists if there is no instance injected in A.
Composition: if two objects are tightly coupled and one can not exists without second.
Class A{
B b;
A(B b){
this.b = b;
}
}
Spring DI: In spring if we are using @Autowired
annotation over a member then this member is required before instantiation of object.
Class A{
@Autowired */ now this member is required before creating of object of A.
B b;
}
Query: So from the above facts we can think Spring DI
as a composition here .I am asking this question because in a interview I had a discussion over it and as per the interviewer Spring
is using Aggregation
here. Could any one please clarify if I am missing or not getting some thing here.
I think it's depend on B scope. If B is singletone then B manage itslef life cycle, so the relation between A and B is Aggregation. If B is not singletone (prototype) then every time A is creating a new instance of B created and injected into A and A manage B life cycle, so the relation between A and B in this scenario ll be Composition
I think, in Spring
Autowire
means more Aggregation
when classes service each other.
For example in MVC
design pattern in Service layer . you may have two Service class that service each other.like Teacher
that teach student and Student
learn from teacher.for implement sample like this you should have two classes like below:
Class Teacher(){
public void teach(Lesson lesson,Student student){
//...
}
}
Class Student(){
@Autowire
private ITeacher iTeacher;
public void learn(Lesson lesson){
iTeacher.teach(lesson,this);
//...
}
}
As you see Student
depends to interface
of Teacher
. and Spring
choose which implement of Interface
choose for injection.From this point of view, beans not coupled together and you can remove and replace implementation by another.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.