引入 aop包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
1.新建注解 DS
package com.example.abstractroutingdatasource.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 在方法上使用,用於指定使用哪個數據源 * * @version v.0.1 */ @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface DS { String value(); }
2.新建AOP DataSourceAspect
package com.example.abstractroutingdatasource.config; import com.sun.corba.se.impl.orb.DataCollectorBase; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Aspect @Order(-10)//保證該AOP在@Transactional之前執行 @Component public class DataSourceAspect { /* * @Before("@annotation(ds)") * 的意思是: * @Before:在方法執行之前進行執行: * @annotation(targetDataSource): * 會攔截注解targetDataSource的方法,否則不攔截; */ // @Before("execution(* com.example.*.dao..*.*(..))") @Before("@annotation(ds)") public void changeDataSource(JoinPoint point,DS ds) throws Throwable { //獲取當前的指定的數據源; String dsId =ds.value(); //如果不在我們注入的所有的數據源范圍之內,那么輸出警告信息,系統自動使用默認的數據源。 DatabaseContextHolder.setDatabaseType(dsId); } @After("@annotation(ds)") public void restoreDataSource(JoinPoint point, DS ds) { System.out.println("Revert DataSource : {} > {}"+ds.value()+point.getSignature()); //方法執行完畢之后,銷毀當前數據源信息,進行垃圾回收。 DatabaseContextHolder.ClearDataBaseType(); } }
3.在dao 上加注解
package com.example.abstractroutingdatasource.dao; import com.example.abstractroutingdatasource.config.DS; import com.example.abstractroutingdatasource.config.DatabaseContextHolder; import com.example.abstractroutingdatasource.entity.UcUser; import com.example.abstractroutingdatasource.mapper.UcUserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.net.UnknownHostException; @Repository public class UcUserDao { @Autowired private UcUserMapper ucUserMapper; @DS(value="1") public UcUser selectOne(String id,String ds ){ // DatabaseContextHolder.setDatabaseType(ds); //手動設置庫 return ucUserMapper.getUser(id); } @DS(value="2") public UcUser selectOne2(String id,String ds ){ // DatabaseContextHolder.setDatabaseType(ds); //手動設置庫 return ucUserMapper.getUser(id); } }
4.完成,啟動應用訪問頁面 數據源會自動切換
demo 鏈接: https://pan.baidu.com/s/1rpC7lMxF_ENW_zLr7MGlBQ
