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.
package com.jdriven;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AutowiredCapabilityBean
{
//The InjectableBean can be made final
private final InjectableBean injectableBean;
//The InjectableBean is autowired byType and is required.
//An error is thrown when no bean or multiple beans of InjectableBean exist
@Autowired
public AutowiredCapabilityBean(InjectableBean injectableBean) {
this.injectableBean = injectableBean;
}
}
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.
package com.jdriven;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AutowiredCapabilityBean
{
private InjectableBean injectableBean;
//No explicit constructor is needed. The default constructor is used.
//The InjectableBean is autowired byType, but is not required.
@Autowired
public void setInjectableBean(InjectableBean injectableBean) {
this.injectableBean = injectableBean;
}
}
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.
package com.jdriven;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AutowiredCapabilityBean
{
//The InjectableBean is autowired byType and is required.
@Autowired
private InjectableBean injectableBean;
//No explicit constructor is needed. The default constructor is used.
}