0

I was wondering what is the difference between the below solutions, why using solution 2? any benefits?

Solution 1:

public A {
  @Autowire
  private B b;
}

public B {
  ...
}

Solution 2:

public A {
  private B b;
  
  @Autowire
  public A(B b) {
     this b=b;
  }
}

public B {
  ...
}```
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29

1 Answers1

0

So, if you initialize your bean by property injection you can get not initialized bean in runtime for different reasons. That may be NPE in Runtime. But if you use the constructor's injection its will be a bootstrap exception. If you try to inject null argument dependency into the constructor potential problem finds faster. It's "fail-fast" an idea. Also, if you have a circular dependency your application fails in bootstrap. You want to know about it early.

Dmitrii B
  • 2,672
  • 3
  • 5
  • 14