views:

26

answers:

2

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?

+1  A: 

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;
}
Arthur Ronald F D Garcia
That is possible but it would automatically inject all the 'SomeListenerInterface' beans in all beans that declare this attribute. Anyway, thanks for the info, I didnt knew about this attribute.
Thiado de Arruda
+1  A: 

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.

skaffman