我在项目的主模块中有一个由 Spring 管理的接口(interface)的实现列表:
<bean id="mail-properties-service" class="com.mail.wrapper.MailPropertiesWrapper" init-method="flushProperties">
<property name="propertiesService" ref="application-properties-service"/>
</bean>
<bean id="record-properties-service" class="com.record.wrapper.RecordPropertiesWrapper" init-method="flushProperties">
<property name="propertiesService" ref="application-properties-service"/>
</bean>
<bean id="admin-properties-service" class="com.admin.wrapper.SystemAdminPropertiesWrapper" init-method="flushProperties">
<property name="propertiesService" ref="application-properties-service"/>
</bean>
<bean id="user-properties-service" class="com.user.wrapper.UserAdminPropertiesWrapper" init-method="flushProperties">
<property name="propertiesService" ref="application-properties-service"/>
</bean>
<bean id="email-campaign-properties-service" class="com.email.wrapper.EmailCampaignPropertiesWrapper" init-method="flushProperties">
<property name="propertiesService" ref="application-properties-service"/>
</bean>
<util:list id="properties-wrappers" value-type="com.wrapper.AbstractPropertiesWrapper">
<ref bean="mail-properties-service"/>
<ref bean="record-properties-service"/>
<ref bean="admin-properties-service"/>
<ref bean="user-properties-service"/>
<ref bean="email-campaign-properties-service"/>
</util:list>
通用包装器管理器使用此列表在属性更改时发出明确的缓存指令,以及其他事情。
我还有项目的扩展,例如 SOP 模块。在 SOP 模块的 applicationContext.xml 文件中的某个地方有这样的东西会很好:
<bean id="sop-properties-service" class="com.sop.wrapper.SOPPropertiesWrapper" init-method="flushProperties">
<property name="propertiesService" ref="application-properties-service"/>
</bean>
<bean ref="properties-wrappers">
<add-item ref="sop-properties-service"/>
</bean>
这样,主项目配置就不必知道 SOP 模块,模块可以将它的包装器添加到包装器列表中。有什么办法吗?
提前致谢。
最佳答案
对于那些处于类似情况的人,我找到了一个简单的解决方案:使用 Spring Autowiring,它将在配置中找到给定接口(interface)或类的所有实现并将它们放入一个数组中。
- 在问题示例中定义 xml 中的属性类(或作为
@Component
)。 在包装器管理器中,添加以下代码。
@Autowired protected AbstractPropertiesWrapper[] wrappers;
wrappers
数组将包含所有包装器,包括 SOP 包装器,而主模块不需要了解有关 SOP 项目的任何信息。
关于java - 将额外的值添加到 spring bean 列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54217816/