![]() ![]() However, Field injection also has the limitation of not being able to use the annotation on fields declared as final/immutable, since these fields must be initialized when the class is instantiated.įurthermore, Field injection is not unit test friendly, you have to use the Spring IoC container to create these beans (and IoC container strong coupling), but unit testing in principle to be fast, start the IoC container is too slow, if it is construction injection, we can complete the bean as a normal class to create objects, just pass directly through the construction. In the past Field injection should be our most used dependency injection method, directly introduce the bean and then use on the variables on the line, but later you will find in IDEA will give a warning “Field injection is not recommended”.īecause Field injection is easy to use, we intentionally or unintentionally introduce many dependencies, and when injecting too many dependencies means that the class takes on too much responsibility, which violates the object-oriented single responsibility principle, and there is no warning no matter how many are introduced, because this approach can be extended indefinitely. ![]() Limitations and alternatives to Field injection Limitations ![]() Constructor injection cannot do this, as it is applied to all constructors.ġ 2 3 4 private DependencyA dependencyA private DependencyB dependencyB įiled injection is the easiest and most convenient way. Setter injection is used if there are optional mutable dependencies, and optional dependencies can be specified with = false). The IoC Service Provider injects the dependent object into the dependent class by calling the setter function provided by the member variable. If there are multiple injection methods and each method only needs to inject a few specified dependencies, then you need to provide multiple overloaded constructors. Disadvantages: When there are many objects to be injected, the constructor parameter list will be long not flexible enough.Pros: You can get a usable object after object initialization, and unit tests can be instantiated without starting a DI container using Mock.Private DependencyA dependencyA private DependencyB dependencyB // is not required, a new feature was added in Spring 4.x: if the class only provides a constructor with parameters, you don't need to write annotations to its internal properties, Spring will automatically inject the properties for public DI (DependencyA dependencyA, DependencyB dependencyB ) ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |