开发者

What is the difference between putting @Autowired to a variable and a method?

开发者 https://www.devze.com 2022-12-10 19:52 出处:网络
Class A { private B instanceB; @Autowired public setInstanceB(B instanceB) { this.instanceB = inst开发者_JS百科anceB;
Class A {

   private B instanceB;

   @Autowired
   public setInstanceB(B instanceB) {
     this.instanceB = inst开发者_JS百科anceB;
   }

}

Above one versus this one.

Class A {

   @Autowired
   private B instanceB;

   public setInstanceB(B instanceB) {
     this.instanceB = instanceB;
   }

}

Will the behavior differ based on the access modifier ?


The difference is the setter will be called if that's where you put it, which is useful if it does other useful stuff, validation, etc. Usually you're comparing:

public class A {
  private B instanceB;

  @Autowired
  public setInstanceB(B instanceB) {
    this.instanceB = instanceB;
  }
}

vs

public class A {
  @Autowired
  private B instanceB;
}

(ie there is no setter).

The first is preferable in this situation because lack of a setter makes mocking/unit testing more difficult. Even if you have a setter but autowire the data member you can create a problem if the setter does something different. This would invalidate your unit testing.

0

精彩评论

暂无评论...
验证码 换一张
取 消