Injection types

There are three options for how dependencies can be injected into a bean:

  1. Through a constructor.

    @Component
    public class MyComponent {
        private final Trade t;
    
        @Autowired
        public MyComponent(Trade t){
           this.t = t;
        }
    }
  2. Through setters or other methods.

    – When you use @Autowired on the setter method.

  3. Through reflection, directly into fields.

    – when you use @Autowired directly on your field

    @Component
    public class MyComponent {
        @Autowired
        private Trade t;
    }

Injection guidelines

A general guideline, which is recommended by Spring (see the sections on Constructor-based DI or Setter-based DI) is the following:

  • For mandatory dependencies or when aiming for immutability, use constructor injection
  • For optional or changeable dependencies, use setter injection
  • Avoid field injection in most cases

Why Field injection is to be avoided?

The reasons why field injection is discouraged are as follows:

  • You cannot create immutable objects, as you can with constructor injection
  • Your classes have tight coupling with your DI container and cannot be used outside of it
  • Your classes cannot be instantiated (for example in unit tests) without reflection. You need the DI container to instantiate them, so your test is not actually a ‘unit’ test, but integration test!
  • It is really easy to have like ten dependencies. If you were using constructor injection, you would have a constructor with ten arguments, which would signal that something is wrong. But you can add injected fields using field injection indefinitely. Having too many dependencies is a red flag that the class usually does more than one thing, and that it may violate the Single Responsibility Principle.

Summary

  • Depending on your needs, you should primarily use constructor injection or some mix of constructor and setter injection.
  • Field injection has many drawbacks and should be avoided.

Reference: https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it