Java Reference
In-Depth Information
<beans ...>
...
<bean id="sequenceGenerator"
class="com.apress.springenterpriserecipes.sequence.SequenceGenerator">
<property name="initial" value="100000" />
<property name="suffix" value="A" />
</bean>
<bean id="datePrefixGenerator"
class="com.apress.springenterpriserecipes.sequence. DatePrefixGenerator">
<property name="pattern" value="yyyyMMdd" />
</bean>
</beans>
By default, all the properties with @Autowired are required. When Spring can't find a matching
bean to wire, it will throw an exception. If you want a certain property to be optional, set the required
attribute of @Autowired to false . Then when Spring can't find a matching bean, it will leave this
property unset.
package com.apress.springenterpriserecipes.sequence;
import org.springframework.beans.factory.annotation.Autowired;
public class SequenceGenerator {
...
@Autowired(required = false)
public void setPrefixGenerator(PrefixGenerator prefixGenerator) {
this.prefixGenerator = prefixGenerator;
}
}
In addition to the setter method, the @Autowired annotation can also be applied to a constructor.
Then Spring will attempt to find a bean with the compatible type for each of the constructor arguments.
package com.apress.springenterpriserecipes.sequence;
import org.springframework.beans.factory.annotation.Autowired;
public class SequenceGenerator {
...
@Autowired
public SequenceGenerator(PrefixGenerator prefixGenerator) {
this.prefixGenerator = prefixGenerator;
}
}
The @Autowired annotation can also be applied to a field, even if it is not declared as public . In this
way, you can omit the need of declaring a setter method or a constructor for this field. Spring will inject
the matched bean into this field via reflection. However, annotating a non-public field with @Autowired
will reduce code testability because the code will be difficult to unit test (there's no way black-box testing
can manipulate that state, such as with mock objects).
Search WWH ::




Custom Search