Java Spring:基于Xml的按接口类型自动连接bean列表
使用Spring,可以通过接口类注入bean列表,如:Java Spring:基于Xml的按接口类型自动连接bean列表,java,spring,list,interface,autowired,Java,Spring,List,Interface,Autowired,使用Spring,可以通过接口类注入bean列表,如: @Component public class Service { @Autowire private List<InterfaceType> implementingBeans; ... } @组件 公务舱服务{ @自动连线 私有列表实现bean; ... } 实现此接口的所有已定义bean都将出现在此列表中 基于注释的方法对我来说是不可能的,因为服务类位于一个模块中,该模块不能具有spring依赖项 我需要通
@Component
public class Service {
@Autowire
private List<InterfaceType> implementingBeans;
...
}
@组件
公务舱服务{
@自动连线
私有列表实现bean;
...
}
实现此接口的所有已定义bean都将出现在此列表中
基于注释的方法对我来说是不可能的,因为服务类位于一个模块中,该模块不能具有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>
??? 告诉spring创建一个列表bean,解析interfaceType的所有bean。
有人知道如何解决这个问题吗
编辑:此外,有多个spring应用程序使用此服务。因此,最好的解决方案是完全通过xml配置来处理这个szenario。然后,我可以将xml部分复制到所有需要它的spriong应用程序
我希望避免使用一种初始值设定项bean,这种bean会注入服务,然后必须复制到所有spring应用程序中
问候。仅XML解决方案只需您声明一个“外部”类型的
,并提供autowire
值“byType”
控制bean属性是否“自动连接”。这是一个
不需要对bean引用进行编码的自动逻辑过程
显式地在XMLBean定义文件中,而不是在Spring中
容器计算出依赖项。[……]
InterfaceType
bean,但实际字段的类型是List
,Spring将能够动态实例化一个,并将所有InterfaceType
bean添加到其中,然后注入它
您的XML看起来就像
<bean id="service" class="...Service" autowire="byType">
</bean>
Spring将创建BeanTDO
bean,注入所有类型为InterfaceType
的bean。然后,它将创建服务
bean,并将其属性从bean设置为的实现bean
属性
对问题的评论如下:
为了更符合JSR330,Spring引入了对JavaEE的javax.inject
包的支持。您现在可以使用@javax.inject.inject
而不是@Autowired
注释注入目标。类似地,您可以使用@Named
而不是@Component
它可以有javax.inject
依赖项吗?您可以使用@Inject
而不是@Autowired
。不错,这很有效。(将您的评论转换为答案以获取业力;)
@Component(value = "beanDTO")
public class BeanDTO {
@Autowire
private List<InterfaceType> implementingBeans;
public List<InterfaceType> getImplementingBeans() {
return implementingBeans;
}
}
<bean id="service" depends-on="beanDTO" class="...Service">
<property name="implementingBeans" value="{beanDTO.implementingBeans}" />
</bean>