Spicy Spring : Different ways of Autowiring

I would like to show different ways of using Spring’s @Autowired annotation: Constructor, Method and Field autowiring.
The examples I show are all a form of byType autowiring mode (constructor autowiring mode is Analogous to byType). Take a look at the Spring Reference guide for more information on the Autowiring modes.

Constructor Autowiring

Create a constructor with a dependent bean as constructor parameter and add the @Autowired annotation to the constructor. A big advantage of autowiring by constructor is that the field can be made final, and therefore may not be changed after construction.

Method Autowiring

Create a setter method for the dependent bean and add the @Autowired annotation to the setter method. A disadvantage of using Method autowiring is that the setter can be called in production code, overriding the bean accidentally.

Field Autowiring

Create a field (member variable) for the dependent bean and add the @Autowired annotation to the field. This way of Autowiring has less code, but takes more effort to test the AutowiredCapabilityBean with an implementation of the InjectableBean, since there is no constructor and no setter for it.

One thought on “Spicy Spring : Different ways of Autowiring

  1. Pingback: Links & reads from 2015 Week 13 | Martin's Weekly Curations

Leave a Reply

Your email address will not be published. Required fields are marked *