The previous article, " annotation-based spring multi-data source configuration and use ," allows you to specify a data source by adding @datasource annotations on a class or method. The advantage of this approach is that the control is granular and more flexible.
The disadvantage is that when the project sub-module development, perhaps a module only access the same data source, in this scenario, if the use of annotations will be in this module all the DAO interface to add annotations @datasource, it will appear cumbersome.
Wouldn't it be better if you could configure it directly in a configuration file without having to add annotations to each class? Of course it is also possible to ^_^.
First, create an AOP slice, named DataSourceAspect2, with the following code:
1 Public classDataSourceAspect2 {2 3 /**4 * Set data source DataSource15 * 6 * @param Point7 */8 Public voidSetDataSource1 (Joinpoint point) {9Dynamicdatasourceholder.setdatasource ("DataSource1");Ten } One A /** - * Set data source DataSource2 - * the * @param Point - */ - Public voidSetDataSource2 (Joinpoint point) { -Dynamicdatasourceholder.setdatasource ("DataSource1"); + } - +}
Then, configure the bean and intercept rules for this slice, and the XML is configured as follows:
1 <BeanID= "DataSourceAspect2"class= "Com.test.context.datasource.DataSourceAspect2" />2 <Aop:config> 3 <Aop:aspectref= "DataSourceAspect2"> 4 <!--intercept all methods under the DS1 module -5 <Aop:pointcutID= "Datasource1pointcut"expression= "Execution (* com.test.ds1.*.* (..))" />6 <!--intercept all methods under the DS2 module - 7 <Aop:pointcutID= "Datasource2pointcut"expression= "Execution (* com.test.ds2.*.* (..))" /> 8 <!--after intercepting the DS1 module, call the SetDataSource1 in DataSourceAspect2 before the method executes to set the data source to be identified as DataSource1 -9 <Aop:beforePointcut-ref= "Datasource1pointcut"Method= "SetDataSource1" /> Ten <!--after intercepting the DS2 module, call the SetDataSource2 in DataSourceAspect2 before the method executes to set the data source to be identified as DataSource2 - One <Aop:beforePointcut-ref= "Datasource1pointcut"Method= "SetDataSource2" /> A </Aop:aspect> - </Aop:config>
Once this is configured, the DAO under each module will only access the specified data source. If you increase the data source DataSource3 later, add a method SetDataSource3 (Joinpoint point) in the DataSourceAspect2 class,
and add a similar interception rule to the above configuration.
If the DS1 module is configured using XML and the data source is DataSource1, and a method A in the DS1 module needs to access the data source DataSource2, you can specify the data source separately on a using annotations @datasource.
That is, annotations and XML configuration can be used at the same time (but not recommended), as to which of the two higher priority, you can configure the order parameter in the Aop:aspect to specify.
XML-based spring multi-data source configuration and usage