Spring autowiring setter/constructor PROs and CONs

前端 未结 4 992
别跟我提以往
别跟我提以往 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 16:10

    Playing the devil advocate long after everyone voted for field injection, here are some advantages for using constructors gathered from polling coworkers around:

    • allows to use final and enforce immutability
    • it is a little less likely to forget to annotate an injected property in the constructor than as a field
    • makes it harder for someone to casually construct an object that should be constructed via the injector

    I still like the fact that if I need an annotated field in another class, I can just do a copy-paste and be done with it as opposed to adding it to the constructor, but it is only a secondary consideration.

提交回复
热议问题