Spring bean xml 配置继承

来源:互联网 发布:淘宝火影忍者手游cdk 编辑:程序博客网 时间:2024/05/21 10:38


本人最近刚到一家新公司,在之前都使用spring 注解配置的方式来写代码的(个人比较喜欢注解的方式)。

但是由于接手的项目是用xml的方式,对于xml配置的方式比较不熟悉。

现在要整合hibernate试用两个数据源(A,B) , DAO层都继续一个父类(假如父类为BasicDaoImpl),该父类又包含  one,two,three属性。

xml注入bean是使用autowire="byType",根据类型注入。


<bean id="one" class="com.xxx.One"><property name="dataSource" value="dataSource" /></bean><bean id="two" class="com.xxx.Two"><property name="dataSource" value="dataSource" /></bean><bean id="three" class="com.xxx.Three"><property name="dataSource" value="dataSource" /></bean><bean id="oneDao" class="com.xxx.dao.OneDaoImpl" autowire="byType" />

但是 one,two,three都依赖数据源,所以必须明确指定是某个数据源.

<bean id="dataSourceA" class="com.alibaba.druid.pool.DruidDataSource" /><bean id="dataSourceB" class="com.alibaba.druid.pool.DruidDataSource" /><bean id="oneA" class="com.xxx.OneA"><property name="dataSource" value="dataSourceA" /></bean><bean id="twoA" class="com.xxx.TwoA"><property name="dataSource" value="dataSourceA" /></bean><bean id="threeA" class="com.xxx.ThreeA"><property name="dataSource" value="dataSourceA" /></bean><bean id="oneB" class="com.xxx.OneB"><property name="dataSource" value="dataSourceB" /></bean><bean id="twoB" class="com.xxx.TwoB"><property name="dataSource" value="dataSourceB" /></bean><bean id="threeB" class="com.xxx.ThreeB"><property name="dataSource" value="dataSourceB" /></bean><bean id="oneDao" class="com.xxx.dao.OneDaoImpl"><property name="one" value="oneA" /><property name="two" value="twoA" /><property name="three" value="threeA" /></bean><bean id="twoDao" class="com.xxx.dao.DaoImpl"><property name="one" value="oneB" /><property name="two" value="twoB" /><property name="three" value="threeB" /></bean>


但是 one,two,three都依赖数据源,所以必须明确指定是某个数据源

<property name="one" value="oneA" /><property name="two" value="twoA" /><property name="three" value="threeA" />

后面找到资料:http://www.yiibai.com/spring/spring-bean-configuration-inheritance.html,用抽象继承的方式,免去以上重复的配置

<bean id="basicDaoImplA" class="com.xxx.BasicDaoImpl"abstract="true"><property name="one" value="oneA" /><property name="two" value="twoA" /><property name="three" value="threeA" /></bean><bean id="basicDaoImplB" class="com.xxx.BasicDaoImpl" abstract="true"><property name="one" value="oneB" /><property name="two" value="twoB" /><property name="three" value="threeB" /></bean>
<bean id="oneDao" class="com.xxx.dao.OneDaoImpl" parent="basicDaoImplA"/><bean id="twoDao" class="com.xxx.dao.TwoDaoImpl" parent="basicDaoImplB"/>


抽象类需要配置abstract="true"。

还有其他类型的模版配置,可以点击查看资料

记录一下,第一次的写博客,请指教批评。