Spring autowiring setter/constructor PROs and CONs

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

    If you weren't using autowiring, there is a big difference between constructor and setter injection. You write the XML differently in order to inject the dependencies. And setter injection dependencies are optional while constructor injection dependencies are not.

    With autowiring, the only reason I can think of is to avoid a circular dependency problem. If A has B has an autowired dependency to the constructor and B has the same for A, we can't instantiate either of them. Giving one a setter dependency could help with that.

提交回复
热议问题