Java – what’s the difference between converting @ Autowired to a variable and a method?
•
Java
Class A {
Class A { private B instanceB; @Autowired public setInstanceB(B instanceB) { this.instanceB = instanceB; } }
The upper one and this one
Class A { @Autowired private B instanceB; public setInstanceB(B instanceB) { this.instanceB = instanceB; } }
Does the behavior vary depending on the access modifier?
Solution
The difference is that the setter will be called, if this is where you place it, it is useful, if it does other useful things, validation, etc Usually you are comparing:
public class A { private B instanceB; @Autowired public setInstanceB(B instanceB) { this.instanceB = instanceB; } }
VS
public class A { @Autowired private B instanceB; }
(i.e. there is no setter)
In this case, the first is the best, because the lack of installers makes mockery / unit testing more difficult Even if you have a setter, you can automatically connect data members. If the setter does different things, you can create a problem This will invalidate your unit test
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码