使用Spring,可以通过接口类注入bean列表,如:
@Component
public class Service {
@Autowire
private List<InterfaceType> implementingBeans;
...
}
实现此接口的所有已定义bean都将出现在此List中。
基于注释的方法对我来说是不可能的,因为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>
有谁知道如何解决这个问题?
编辑:此外,有多个弹簧应用程序使用此服务。所以最好的解决方案是通过xml配置完全处理这个szenario。然后我可以将xml部分复制到需要它的所有spriong应用程序。
我想避免使用一种初始化bean来获取注入的服务,然后必须将其复制到所有spring应用程序。
亲切的问候。
答案 0 :(得分:2)
在 具有Spring依赖关系的模块中,创建DTO
@Component(value = "beanDTO")
public class BeanDTO {
@Autowire
private List<InterfaceType> implementingBeans;
public List<InterfaceType> getImplementingBeans() {
return implementingBeans;
}
}
然后使用SpEL从implementingBeans
bean中检索beanDTO
的值。
<bean id="service" depends-on="beanDTO" class="...Service">
<property name="implementingBeans" value="{beanDTO.implementingBeans}" />
</bean>
Spring将创建BeanTDO
bean,注入所有类型为InterfaceType
的bean。然后它将创建service
bean并从beanDTO
的{{1}}属性设置其属性。
编辑(来自对问题的评论)
为了更加符合JSR 330,Spring引入了对Java EE implementingBeans
包的支持。您现在可以使用javax.inject
而不是@javax.inject.Inject
为注射目标添加注释。同样,您可以使用@Autowired
代替@Named
。 The documentation has more details.