Any differences between the three dependency injection methods?

Is the third most common bean injection method? Any differences between the two?

  • Bean Entering constructor parameters:

     public class Checkout {
        private final ShoppingCart cart;
    
        @Inject
        public Checkout(ShoppingCart cart) {
          this.cart = cart;
        }
    }
    
  • Inserting an initializer method parameter:

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

    public class Checkout {
       private @Inject ShoppingCart cart;
    }
    
+4
source share
2 answers

An opinion based answer, but it seems that injection through the constructor is best for the following reasons.

  • You can perform a null constructor check, which can lead to incorrect error handling elsewhere in your class.
  • You can more easily inject mocks into your class for testing.
  • You cannot forget to indicate the dependency.
  • This is not like magic.
+3

, , . - , - .

, :

    • beans ,
    • beans bean ( )
    • : beans ; , , bean
    • beans ( , Weld , )
    • , - , , bean
    • , bean "
    • , , , bean
    • bean ( )
    • : , .

. , , .

. , .

0

Source: https://habr.com/ru/post/1653554/


All Articles