What is the difference between putting @Autowired to a variable and a method?
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.
精彩评论