一、首先我們添加添加aop依賴,此依賴已包含AspectJ相關依賴包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、編寫攔截規則要攔截到的註解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
String name() default "";
}
這裏對元註解做個說明:元註解是指註解的註解,包括@Retention @Target @Document @Inherited四種。
五、編寫切面
@Aspect
@Component
public class DataSourceAspect implements Ordered
{
protected Logger logger = LoggerFactory.getLogger(getClass());
//
@Pointcut("@annotation(com.unqd.ims.datasources.annotation.DataSource)")
public void dataSourcePointCut() {
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DataSource ds = method.getAnnotation(DataSource.class);
if(ds == null){
DynamicDataSource.setDataSource("first");
logger.debug("set datasource is " + "first");
}else {
DynamicDataSource.setDataSource(ds.name());
logger.debug("set datasource is " + ds.name());
}
try {
return point.proceed();
} finally {
DynamicDataSource.clearDataSource();
logger.debug("clean datasource");
}
}
AOP註解說明:
@Aspect 定義切面:切面由切點和增強(引介)組成(可以包含多個切點和多個增強),它既包括了橫切邏輯的定義,也包括了連接點的定義,SpringAOP就是負責實施切面的框架,它將切面所定義的橫切邏輯織入到切面所指定的鏈接點中。
@Pointcut 定義切點:切點是一組連接點的集合。AOP通過“切點”定位特定的連接點。通過數據庫查詢的概念來理解切點和連接點的關係再適合不過了:連接點相當於數據庫中的記錄,而切點相當於查詢條件。
@Before :在目標方法被調用之前做增強處理,@Before只需要指定切入點表達式即可。
@AfterReturning : 在目標方法正常完成後做增強,@AfterReturning除了指定切入點表達式後,還可以指定一個返回值形參名returning,代表目標方法的返回值。
@Afterthrowing: 主要用來處理程序中未處理的異常,@AfterThrowing除了指定切入點表達式後,還可以指定一個throwing的返回值形參名,可以通過該形參名來訪問目標方法中所拋出的異常對象。
@After: 在目標方法完成之後做增強,無論目標方法時候成功完成。@After可以指定一個切入點表達式。
@Around: 環繞通知,在目標方法完成前後做增強處理,環繞通知是最重要的通知類型,像事務,日誌等都是環繞通知,注意編程中核心是一個ProceedingJoinPoint。