Spring autowiring setter/constructor PROs and CONs

不问归期 提交于 2019-12-20 12:36:51

问题


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

See the following examples:

public class Example{
   private Logger log;
   // constructor wiring
   @Autowired 
   public Example(Logger log){
      this.log = log;
   }
}

public class Example{
   // setter wiring
   @Autowired 
   private Logger log;
}

回答1:


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.




回答2:


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.




回答3:


A specific reason for annotating setters: The setters can then save bean references to static variables.




回答4:


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.



来源:https://stackoverflow.com/questions/5686462/spring-autowiring-setter-constructor-pros-and-cons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!