Java Stereotype Series - The Way of Dependency Injection

There are three ways of dependency injection:

  • constructor injection
    • Advantages: Fix the order of dependency injection and solve the problem of circular dependency.
    • Cons: Can look bloated when injected too much.
  • setter injection
    • Advantages: Dependencies are only injected when the object needs to be injected, not when it is initialized.
    • Disadvantage: Objects cannot be made final.
  • attribute injection
    • Pros: Simple, highly readable.
    • Disadvantages: It may lead to circular dependencies, duplicate name dependencies, and empty dependencies, and internal values ​​may be modified by reflection if they are relied on by multiple parties.

The Spring team generally recommends using constructor injection because it allows an application component to be implemented as an immutable object and ensures that required dependencies are not null. Additionally constructor injected components always return a fully initialized client client (call). Note though, that a large number of constructor parameters is a bad coding practice, which means that the class may have too many responsibilities and should be refactored to better address proper separation of concerns.

For attribute injection, there are two annotation methods: @Autowiredand @Resource, the difference is as follows:

  • @AutowiredAnnotations are provided by Spring; @Resourceannotations are provided by J2EE
  • @AutowiredAssemble by type, and assemble by name when there are multiple beans of the same type; @Resourceyou can choose to assemble by type or name through configuration parameters, and the default is by name

There are also differences in usage between the two:

  • @AutowiredBy default, the dependent object must be required to exist. If you want to allow null values, you can set its required attribute to false. If you want to use name assembly, you can @Qualifieruse it in combination with annotations.
  • @ResourceBy default, it is assembled according to the name, and the name can be specified through the name attribute. If the name attribute is not specified, when the annotation is written on the field, the default field name is used for name search. If the annotation is written on the setter method, the attribute name is used for assembly by default. Wiring is done by type when no bean matching the name is found. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.

If you use attribute injection, it is generally recommended to use @Resourceannotations, so that you don’t need to write setter methods, and this annotation belongs to J2EE, which reduces the coupling with Spring.

If you are interested in learning more about it, please visit my personal website: Yetong Space

おすすめ

転載: blog.csdn.net/tongkongyu/article/details/129368279