Is the 3rd one most common way to inject a bean? Any differences between them?
Bean constructor parameter injection:
public class Checkout { private final ShoppingCart cart; @Inject public Checkout(ShoppingCart cart) { this.cart = cart; } }
Initializer method parameter injection:
public class Checkout { private ShoppingCart cart; @Inject void setShoppingCart(ShoppingCart cart) { this.cart = cart; } }
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.
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:
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.