1、pom文件中導入相關依賴
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
2、創建業務邏輯類
@Service("productService")
public class ProductService {
public void queryProduct() throws Exception {
// throw new Exception("運行時異常!");
System.out.println("查詢商品信息中!");
}
}
3、創建切面和通知
@Aspect
@Component
public class ProductLog {
/**
* 切點
*/
@Pointcut("execution(public void com.qing.zhao.ProductService.*(..))")
public void pc(){}
/**
* 以下方法都是通知
*/
@Before("pc()")
public void beforQueryProduct(){
System.out.println("查詢商品信息-----前");
}
@After("pc()")
public void afterQueryProduct(){
System.out.println("查詢商品信息-----後");
}
@AfterReturning("pc()")
public void returnQueryProduct(){
System.out.println("查詢商品信息-----正常返回");
}
@AfterThrowing("pc()")
public void exceptionQueryProduct(){
System.out.println("查詢商品信息-----異常返回");
}
@Around("pc()")
public void aroundQueryProduct(ProceedingJoinPoint joinPoint){
try {
System.out.println("查詢商品信息-----前");
joinPoint.proceed();
System.out.println("查詢商品信息-----後");
} catch (Throwable throwable) {
System.out.println("查詢商品信息-----異常返回");
throwable.printStackTrace();
}finally {
System.out.println("查詢商品信息-----最終返回");
}
}
4、創建配置類
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class Configration {
}
5、運行結果
- 無異常正常返回:
- 有異常返回:
-
環繞無異常正常返回:
-
環繞有異常返回: