简体   繁体   中英

Spring: Xml based Autowiring a list of beans by interface type

With Spring it is possible to inject a list of beans by the interface class like:

@Component
public class Service {
  @Autowire
  private List<InterfaceType> implementingBeans;
  ...
}

All defined beans that implement this interface will be present in this List.

The annotation based approach is not possible for me, as the Service class is in a module that must not have spring dependencies.

I need to use this mechanism from outside via xml configuration.

<bean id="service" class="...Service">
  <property name="implementingBeans">
    ??? tell spring to create a list bean that resolves all beans of the interfaceType.
  </property>
</bean>

Does anyone know how to solve this?

EDIT: Additionally, there are more than one spring applications that use this service. So the best solution would be to handle this szenario completely via xml configuration. I can then copy the xml parts to all spriong applications that need this.

I want to avoid having a kind of initializer bean that gets the service injected and must then be copied to all spring applications.

Kind regards.

In the module that does have Spring dependencies, create a DTO

@Component(value = "beanDTO")
public class BeanDTO {
    @Autowire
    private List<InterfaceType> implementingBeans;

    public List<InterfaceType> getImplementingBeans() {
        return implementingBeans;
    }
}

and then use SpEL to retrieve the value of implementingBeans from the beanDTO bean.

<bean id="service" depends-on="beanDTO" class="...Service">
    <property name="implementingBeans" value="{beanDTO.implementingBeans}" />
</bean>

Spring will create the BeanTDO bean, inject all the beans that are of type InterfaceType . It will then create the service bean and set its property from beanDTO 's implementingBeans property.


Edit (from comment on question)

In an effort to be more JSR 330 compliant, Spring has introduced support for Java EE's javax.inject package. You can now annotate your injection targets with @javax.inject.Inject instead of @Autowired . Similarly, you can use @Named instead of @Component . The documentation has more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM