tags:

views:

157

answers:

1
Class A {

   private B instanceB;

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

}

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 ?

+5  A: 

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.

cletus