2

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.

Vicky
  • 1,135
  • 1
  • 17
  • 37

2 Answers2

0

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

Arya
  • 91
  • 4
  • but anyhow object of 'A' can not be exists with the object of 'B' and if the B's scope is singleton then also at the first `getBean` call B will going to instantiate. – Vicky Jul 18 '18 at 07:37
  • your definition about Composition is wrong. take a look at https://stackoverflow.com/questions/885937/what-is-the-difference-between-association-aggregation-and-composition – Arya Jul 18 '18 at 07:46
  • I am not sure why you are saying it wrong, try to take it as (A -> Address and B-> City). – Vicky Jul 18 '18 at 07:51
  • City is parent and Address is child, you should say A-> City and B-> Address. if we think A as child and B as parent existence of A is always depend on B. – Arya Jul 18 '18 at 09:51
0

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.

Javad Kargar
  • 1,275
  • 1
  • 12
  • 27