Java Reference
In-Depth Information
How It Works
To ask Spring to auto-wire the bean properties with
@Autowired
or
@Resource
, you have to register an
AutowiredAnnotationBeanPostProcessor
instance in the IoC container. If you are using a bean factory,
you have to register this bean post processor through the API. Otherwise, you can just declare an
instance of it in your application context.
<bean class="org.springframework.beans.factory.annotation.
➥
AutowiredAnnotationBeanPostProcessor" />
Or you can simply include the
<context:annotation-config>
element in your bean configuration
file, and an
AutowiredAnnotationBeanPostProcessor
instance will automatically get registered.
<beans xmlns="
http://www.springframework.org/schema/beans"
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
<context:annotation-config />
...
</beans>
Auto-Wiring a Single Bean of Compatible Type
The
@Autowired
annotation can be applied to a particular property for Spring to auto-wire it. As an
example, you can annotate the setter method of the
prefixGenerator
property with
@Autowired
. Then
Spring will attempt to wire a bean whose type is compatible with
PrefixGenerator
.
package com.apress.springenterpriserecipes.sequence;
import org.springframework.beans.factory.annotation.Autowired;
public class SequenceGenerator {
...
@Autowired
public void setPrefixGenerator(PrefixGenerator prefixGenerator) {
this.prefixGenerator = prefixGenerator;
}
}
If you have a bean whose type is compatible with
PrefixGenerator
defined in the IoC container, it
will be set to the
prefixGenerator
property automatically.
Search WWH ::
Custom Search