lishman levelup
«previous  next»


Getting Started
Form Processing
IoC Container
Hibernate ORM



Autowiring in Spring MVC


In the previous examples, we instantiate a MockWorldService object using the new operator, like this:
 
private WorldService worldService = new MockWorldService();
 
However, to improve flexibility, we will let Spring 'autowire' the implementation using dependency injection.

@Autowired

The @Autowired annotation is used to inform Spring that an object is to be injected at this point.

We can autowire an object directly into a field, even if it is private.
@Autowired
private WorldService worldService;
Or, we could use @Autowired to inject an object into an arbitrary method parameter, like this one:
@Autowired
public void setWorldService(WorldService worldService) {
  this.worldService = worldService;
}
Objects can also be injected into the constructor of another object.
@Autowired
public CountryForm(WorldService worldService) {
  this.worldService = worldService;
}
We can even annotate arrays and typed collections if multiple implementations of a particular type are required.
@Autowired
private WorldService[] worldService;
@Autowired
private Set<WorldService> worldService;

The Required Element

The required element of the @Autowired annotation specifies whether autowiring is optional or mandatory.
@Autowired(required=false)
private WorldService worldService = new MockWorldService();
If no matching WorldService implementation is found by Spring, then MockWorldService is instantiated using the new operator.

An exception will be thrown if there is no appropriate implementation, and required is set to true.
»