上一篇讲了《基于注解的SPRing多数据源配置和使用》,通过在类或者方法上添加@DataSource注解就可以指定某个数据源。这种方式的优点是控制粒度细,也更灵活。
缺点是当有些时候项目分模块开发,可能某一个模块只访问同一个数据源,这种场景下如果使用注解的话就要在这个模块下的所有dao接口都增加注解@DataSource,就会显得繁琐。
如果能直接在配置文件中一次性配置好,不用在每个类都添加注解岂不是更好?当然也是可以的^_^。
首先,再创建一个AOP切面DataSourceaspect2,代码如下:
1publicclassDataSourceAspect2 {23/**4* 设置数据源dataSource15*6*@parampoint7*/8publicvoidsetDataSource1(JoinPoint point) {9DynamicDataSourceHolder.setDataSource("dataSource1");10}1112/**13* 设置数据源dataSource214*15*@parampoint16*/17publicvoidsetDataSource2(JoinPoint point) {18DynamicDataSourceHolder.setDataSource("dataSource1");19}2021}
然后,配置这个切面的bean和拦截规则,xml配置如下:
1<beanid="dataSourceAspect2"class="com.test.context.datasource.DataSourceAspect2"/>2<aop:config>3<aop:aspectref="dataSourceAspect2">4<!--拦截ds1模块下的所有方法-->5<aop:pointcutid="dataSource1Pointcut"expression="execution(* com.test.ds1.*.*(..))"/>6<!--拦截ds2模块下的所有方法-->7<aop:pointcutid=" dataSource2Pointcut"expression="execution(* com.test.ds2.*.*(..))"/>8<!--拦截到ds1模块后,在方法执行前先调用DataSourceAspect2里的setDataSource1设置数据源标识为dataSource1-->9<aop:beforepointcut-ref="dataSource1Pointcut"method="setDataSource1"/>10<!--拦截到ds2模块后,在方法执行前先调用DataSourceAspect2里的setDataSource2设置数据源标识为dataSource2-->11<aop:beforepointcut-ref="dataSource1Pointcut"method="setDataSource2"/>12</aop:aspect>13</aop:config>
这样配置好之后,每个模块下的dao就只访问指定的数据源了。以后如果再增加数据源dataSource3,则在DataSourceAspect2类里增加一个方法setDataSource3(JoinPoint point),
并在上面的配置中增加类似的拦截规则就可以了。
假如使用了xml的方式配置了ds1模块使用数据源dataSource1了,而ds1模块下的某个方法a又需要访问数据源dataSource2,这时可以单独在a上使用注解@DataSource指定数据源。
也就是说注解和xml配置两种方式可以同时使用(但不建议这样),至于两者哪个的优先级更高,可以通过配置aop:aspect里的order参数进行指定。