Normally dependencies are injected via setters by the following configuration (http://static.springsource.org/sprin...beans-beanname) :
开发者_如何转开发<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested <ref/> element -->
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<!-- setter injection using the neater 'ref' attribute -->
<property name="beanTwo" ref="yetAnotherBean"/>
<property name="integerProperty" value="1"/>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Lets say the class examples.ExampleBean
has a collection listeners objects, and the method addListener(SomeListenerInterface)
is the only possible way add listeners. Can I inject listeners declaratively in xml like its done with property setters?
You could probably conjure up some baroque mechanism for doing this all in XML, but the cleanest way to do this is to use a FactoryBean
. You write a class which implement FactoryBean
, and which is responsible for constructing and configuring your target object (see Spring docs). Your FactoryBean
would have the required getters/setters/autowiring, and injects them into the target object.
This is often the cleanest way to handle non-javabeans in Spring, particularly if you cannot modify the target class.
Here goes property Element definition
Property elements correspond to JavaBean setter methods exposed by the bean classes.
To get your goal, you can use @Autowired annotation. It works even when using an arbitrary name
@Autowired
public void inject(SomeListenerInterface someListenerInterface) {
this.someListenerInterface = someListenerInterface;
}
精彩评论