当前位置:网站首页>Field injection is not recommended Autowired

Field injection is not recommended Autowired

2020-11-10 16:08:11 Pluto_Note

Spring 4.x Not recommended at first @Autowired

 Official documents  :1.4.1. Dependency Injection

DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection.

 Reference address :https://docs.spring.io/spring-framework/docs/5.1.3.RELEASE/spring-framework-reference/core.html#beans-factory-collaborators "Dependency Injection 

stack over flow

{
	here are three options for how dependencies can be injected into a bean:

	Through a constructor
	Through setters or other methods
	Through reflection, directly into fields
	You are using option 3. That is what is happening when you use @Autowired directly on your field.

	Field injection drawbacks

	The reasons why field injection is frowned upon are as follows:

	You cannot create immutable objects, as you can with constructor injection
	Your classes have tight coupling with your DI container and cannot be used outside of it
	Your classes cannot be instantiated (for example in unit tests) without reflection. You need the DI container to instantiate them, which makes your tests more like integration tests
	Your real dependencies are hidden from the outside and are not reflected in your interface (either constructors or methods)
	It is really easy to have like ten dependencies. If you were using constructor injection, you would have a constructor with ten arguments, which would signal that something is fishy. But you can add injected fields using field injection indefinitely. Having too many dependencies is a red flag that the class usually does more than one thing, and that it may violate the Single Responsibility Principle.

  	Conclusion

	Depending on your needs, you should primarily use constructor injection or some mix of constructor and setter injection. Field injection has many drawbacks and should be avoided. The only advantage of field injection is that it is more convenient to write, which does not outweigh all the cons.

	link:`https://stackoverflow.com/questions/39890849`
}

版权声明
本文为[Pluto_Note]所创,转载请带上原文链接,感谢