Spring:基于 XML 的自动装配按接口类型的 bean 列表

ser*_*ime 5 java spring interface list autowired

使用 Spring 可以通过接口类注入 bean 列表,例如:

@Component
public class Service {
  @Autowire
  private List<InterfaceType> implementingBeans;
  ...
}
Run Code Online (Sandbox Code Playgroud)

实现此接口的所有已定义 bean 都将出现在此列表中。

基于注释的方法对我来说是不可能的,因为 Service 类位于一个不能具有 spring 依赖关系的模块中。

我需要通过 xml 配置从外部使用这种机制。

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

有谁知道如何解决这个问题?

编辑:此外,有不止一个使用此服务的 spring 应用程序。所以最好的解决方案是通过 xml 配置完全处理这个 szenario。然后我可以将 xml 部分复制到所有需要它的 spriong 应用程序。

我想避免使用一种初始化 bean 来注入服务,然后必须将其复制到所有 spring 应用程序。

亲切的问候。

Sot*_*lis 3

纯 XML 解决方案只需声明<bean>“外部”类型并提供autowire"byType"

控制 bean 属性是否“自动装配”。这是一个自动的过程,其中 bean 引用不需要在 XML bean 定义文件中显式编码,而是由 Spring 容器计算依赖关系。
[...]

  1. "byType" 如果容器中只有一个该属性类型的 bean,则自动装配。如果有多个,则会引发致命错误,并且您无法对该 bean 使用 byType 自动装配。如果没有,就不会发生什么特别的事情。

这个解释有点令人困惑,因为我们期望多个InterfaceTypebean,但实际字段是类型的List,Spring 将能够动态实例化一个 bean 并将所有InterfaceTypebean 添加到其中,然后注入它。

你的 XML 看起来就像

<bean id="service" class="...Service" autowire="byType">
</bean>
Run Code Online (Sandbox Code Playgroud)

我最初建议的解决方案使用了 SpEL。

在确实有Spring依赖的模块中,创建一个DTO

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

    public List<InterfaceType> getImplementingBeans() {
        return implementingBeans;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用SpELimplementingBeans从bean 中检索 的值beanDTO

<bean id="service" depends-on="beanDTO" class="...Service">
    <property name="implementingBeans" value="{beanDTO.implementingBeans}" />
</bean>
Run Code Online (Sandbox Code Playgroud)

Spring将创建BeanTDObean,注入所有类型为 的bean InterfaceType。然后它将创建bean 并根据 的属性service设置其属性。beanDTOimplementingBeans


以下对问题的评论:

为了更加符合 JSR 330,Spring 引入了对 Java EEjavax.inject包的支持。@javax.inject.Inject您现在可以使用而不是注释您的注射目标@Autowired。同样,您可以使用@Named代替@Component. 该文档有更多详细信息。