Spring - Different ways of injecting dependencies

[Updated: Aug 24, 2016, Created: Aug 7, 2016]

There are three possible ways of DI in Spring

  1. Constructor-based: should be used for mandatory dependencies. In constructor, we should assign constructor args to final member fields.

  2. Setter-based: Should be used for optional dependencies.

  3. Field-based: Spring discourages the use of this because it would possibly hide mandatory fields from outside which would otherwise be assigned in the constructor. This would take away the advantage of properly initialized POJO, specially if intended to use outside of Spring container. Even though, we are mostly using field based injection in this series of tutorials to simplify the concept we want to deliver, we suggest the developers to always avoid using field-based DI in real project scenarios.

Example project

Dependencies and Technologies Used:

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Types Of Di Example Select All Download
  • spring-types-of-di
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • di
                  • cons
                • service
                  • impl

    Notice in class we don't have to use @Autowired on the constructor. That's because in the configuration class, we are directly invoking the constructor along with a straight call to orderServiceByProvider1(). We shouldn't worry about calling methods like that in the @Configuration class and thinking that every time a new instance in the calling method will be created, no it won't. As mentioned here all methods annotated with @Bean are proxied so they are not called multiple times because of the default singleton scope.

    Also in above, we are using @ComponentScan, in that case we have to use @Autowired on the constructor. Also in case of multiple instances of the target bean, we have to use @Qualifier to resolve the conflict.

    See Also