[英]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: 使用Spring,可以通过接口类注入bean列表,如:
@Component
public class Service {
@Autowire
private List<InterfaceType> implementingBeans;
...
}
All defined beans that implement this interface will be present in this List. 实现此接口的所有已定义bean都将出现在此List中。
The annotation based approach is not possible for me, as the Service class is in a module that must not have spring dependencies. 基于注释的方法对我来说是不可能的,因为Service类在一个不能具有spring依赖性的模块中。
I need to use this mechanism from outside via xml configuration. 我需要从外部通过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>
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.
所以最好的解决方案是通过xml配置完全处理这个szenario。 I can then copy the xml parts to all spriong applications that need this.
然后我可以将xml部分复制到需要它的所有spriong应用程序。
I want to avoid having a kind of initializer bean that gets the service injected and must then be copied to all spring applications. 我想避免使用一种初始化bean来获取注入的服务,然后必须将其复制到所有spring应用程序。
Kind regards. 亲切的问候。
In the module that does have Spring dependencies, create a DTO 在确实有Spring的依赖模块,创建一个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. 然后利用规划环境地政司要检索的值
implementingBeans
从beanDTO
豆。
<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
. Spring将创建
BeanTDO
bean,注入所有类型为InterfaceType
的bean。 It will then create the service
bean and set its property from beanDTO
's implementingBeans
property. 然后它将创建
service
bean并从beanDTO
的implementingBeans
属性设置其属性。
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. 为了更加符合JSR 330,Spring引入了对Java EE的
javax.inject
包的支持。 You can now annotate your injection targets with @javax.inject.Inject
instead of @Autowired
. 您现在可以使用
@javax.inject.Inject
而不是@Autowired
来注释您的注射目标。 Similarly, you can use @Named
instead of @Component
. 同样,您可以使用
@Named
而不是@Component
。 The documentation has more details. 文档有更多细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.