1.业务层接口
public interface AccountService {
//模拟保存账户
void saveAccount();
//模拟更新账户
void updateAccount(int i);
//模拟删除账户
int deleteAccount();
}
2.业务层实现类
package com.hh.service;
public class AccountServiceImpl implements AccountService {
public void saveAccount() {
System.out.println("执行了保存");
int i=1/0;
}
public void updateAccount(int i) {
System.out.println("执行了更新");
}
public int deleteAccount() {
System.out.println("执行了删除");
return 0;
}
}
3.日志类
import org.aspectj.lang.ProceedingJoinPoint;
public class Logger {
//前置通知
public void beforePrintLog(){
System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志");
}
//后置通知
public void afterReturnPrintLog(){
System.out.println("后置通知Logger类中的afterReturnPrintLog方法开始记录日志");
}
//异常通知
public void afterThrowingPrintLog(){
System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志");
}
//最终通知
public void afterPrintLog(){
System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志");
}
/*
* 环绕通知:
* 配置环绕通知之后,切入点方法没有执行,但是通知方法执行了
* 解决:
* Spring框架为我们提供了一个接口:ProceedingJoinPoint
* 该接口中提供了一个方法procceed(),此方法就相当于明确调用切入点方法
* 该接口可以作为环绕通知接口的参数,在程序执行时,
* 在Spring程序执行时,Spring框架会为我们提供该接口的实现类供我么使用
*/
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object result = null;
try {
Object[] args = pjp.getArgs();//得到方法执行的返回参数
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...前置");
pjp.proceed(args);//明确调用业务层方法
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...后置");
return result;
} catch (Throwable throwable) {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...异常");
throw new RuntimeException(throwable);
}finally {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...最终");
}
}
}
4.配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置Spring的IOC-->
<bean id="accountService" class="com.hh.service.AccountServiceImpl"/>
<bean id="logger" class="com.hh.utils.Logger"/>
<!--配置AOP-->
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<!--配置环绕通知-->
<aop:around method="aroundPrintLog" pointcut-ref="pt"/>
<aop:pointcut id="pt" expression="execution(* com.hh.service.*.*(..))"/>
</aop:aspect>
</aop:config>
</beans>