Spring autowiring setter/constructor PROs and CONs

前端 未结 4 985
别跟我提以往
别跟我提以往 2021-02-05 15:15

When using @Autowired (not xml configuration), could someone compare the set/constructor binding advantages and disadvantages?

See the following examples:



        
4条回答
  •  自闭症患者
    2021-02-05 15:50

    It is entirely a matter of preference.

    Spring frowns upon constructor injection, or at least used to, because thus circular dependencies appear and they are hard to manage (A needs B in constructor, B needs A in constructor).

    One actual difference is that with @Autowired on a field you don't need a setter method, which, on one hand makes the class smaller and easier to read, but on the other hand makes mocking the class a bit uglier.

    I prefer the field injection.

提交回复
热议问题