简体   繁体   中英

Any differences between 3 ways of dependency injection?

Is the 3rd one most common way to inject a bean? Any differences between them?

  1. Bean constructor parameter injection:

      public class Checkout { private final ShoppingCart cart; @Inject public Checkout(ShoppingCart cart) { this.cart = cart; } } 
  2. Initializer method parameter injection:

     public class Checkout { private ShoppingCart cart; @Inject void setShoppingCart(ShoppingCart cart) { this.cart = cart; } } 
  3. Field injection:

     public class Checkout { private @Inject ShoppingCart cart; } 

An opinion-based answer, but it would seem that injecting through the constructor is best for the following reasons.

  • You can null check in the constructor, which might save you some error handling elsewhere in your class.
  • You can more easily inject mocks into your class for testing.
  • You can't forget to supply a dependency.
  • It doesn't look like magic.

Field injection is probably the most common. The reason is pretty obvious - it's the fastest way to connect things make it do something.

As for differences, there are some:

  • constructor injection
    • the only way to access other beans while you initialize this one
    • otherwise while instantiating beans, your bean field ( field injection ) will not yet work
    • example: you need data from other beans while creating this one; based on such data you determine for instance what strategy will this bean use for data storage
  • field injection
    • leads to lazy injection of beans (might be Weld specific, not sure now)
    • means if you don't do any extra work to make it eager, the bean will only actually be accessible once you first invoke a method on it
    • this is a go-to approach if you "just want the bean"
  • initializer method parameter injection
    • you will want this, if you need some extra work done at the moment you inject the bean
    • this event might happen more than once per bean lifecycle (that's what you have scopes for)
    • example of usage: you might want to fire an event once the injection happens

All in all, you are free to use any approach. The story here is that there are some use-cases which couldn't be covered by simple field injection.

This is just from the top of my head and is not exhaustive. I hope it sheds some light on the topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM