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、运行结果
- 无异常正常返回:
- 有异常返回:
-
环绕无异常正常返回:
-
环绕有异常返回: