Java Reference
In-Depth Information
<bean id="datePrefixGenerator"
class="com.apress.springenterpriserecipes.sequence.DatePrefixGenerator">
<property name="pattern" value="yyyyMMdd" />
</bean>
</beans>
Auto-Wiring and Dependency Checking
As you have seen, if Spring finds more than one candidate bean for auto-wiring, it will throw an
UnsatisfiedDependencyException
. On the other hand, if the auto-wiring mode is set to
byName
or
byType
,
and Spring cannot find a matching bean to wire, it will leave the property unset, which may cause a
NullPointerException
or a value that has not been initialized. However, if you want to be notified when
auto-wiring cannot wire your beans, you should set the
dependency-check
attribute to
objects
or
all
.
In that case, an
UnsatisfiedDependencyException
will be thrown whenever auto-wiring doesn't
work.
objects
tells Spring to raise an error when a collaborating bean can't be found in the same bean
factory.
all
tells the container to raise an error when any simple property types (a
String
or a primitive)
expressed as dependencies on a bean haven't been set, in addition to the functionality of
objects
.
<bean id="sequenceGenerator"
class="com.apress.springenterpriserecipes.sequence.SequenceGenerator"
autowire="byName" dependency-check="objects">
<property name="initial" value="100000" />
<property name="suffix" value="A" />
</bean>
1-4. Auto-Wiring Beans with @Autowired and @Resource
Problem
Auto-wiring by setting the
autowire
attribute in the bean configuration file will wire all properties of a
bean. It's not flexible enough to wire particular properties only. Moreover, you can auto-wire beans only
either by type or by name. If neither strategy satisfies your requirements, you must wire your beans
explicitly.
Solution
Spring 2.5 made extensive enhancements to the auto-wiring feature. You can auto-wire a particular
property by annotating a setter method, a constructor, a field, or even an arbitrary method with the
@Autowired
annotation or the
@Resource
annotation defined in JSR-250: Common Annotations for the
Java Platform. That means you have one more option besides setting the
autowire
attribute to satisfy
your requirements. However, this annotation-based option requires you to be using Java 1.5 or higher.
Search WWH ::
Custom Search