我需要使用新的bean定义扩展spring applicatioContext xml文件,然后将对它们的引用添加到list,这是一个bean的属性: 基本applicationContext xml文件:
<bean id="myBean" class="com.example.MyBean">
<property name="providers">
<list>
<ref bean="provider1">
</list>
</property>
</bean>
<bean id="provider1" class="com.example.Provider">
取决于应用程序的实例我有不同的提供程序,所以我需要将它们添加到列表中。现在我在数据库中有了额外的bean定义,并使用BeanFactoryPostProcessor
将它们添加到上下文中,然后将对它们的引用添加到提供者列表中。但我在@Transactional
和自动事务管理(myBean
)上使用tx:annotation-driven
注释,并且由于使用BeanFactoryPostProcessor
,因此不会处理事务注释。
所以我需要另一种方法来扩展应用程序上下文,然后扩展提供程序列表。我可以用什么?
我的想法是让xml文件在开头是空的,然后用数据库中的数据填充它,然后以某种方式在applicationContext中导入它。有可能吗?
感谢您的帮助
答案 0 :(得分:0)
在MyBean类中使用@PostConstruct方法,从数据库加载和填充提供者列表。
@PostConstruct
public void initialize() {
providers.addAll(providerService.findAll());
}
将所有与数据库相关的代码放入Service / Dao类并使用@Transactional
注释对其进行注释
答案 1 :(得分:0)
您可以通过多种方式覆盖或扩展bean定义。简而言之,这是一种方式..
主要应用程序上下文xml:
<bean id="myBaseBean" class="com.example.MyBean" abstract="true">
<property name="providers">
<list merge="true">
<ref bean="provider1" />
</list>
</property>
</bean>
<!-- default bean definition -->
<bean id="myBean" parent="myBaseBean">
<property name="providers">
<list merge="true">
</list>
</property>
</bean>
<bean id="provider1" class="com.example.Provider">
一些extendedApplication Context xml:
<bean id="myBean" parent="myBaseBean">
<property name="providers">
<list merge="true">
<ref bean="someOtherProvider" />
</list>
</property>
</bean>
<!-- bean definition of some other provider -->
这与Transactions
无关你必须像往常一样为每个其他bean处理事务。
注意:根据您在创建ApplicationContext
时提到的文件名的顺序,将加载/覆盖所有应用程序上下文文件。