背景:有时候代码执行,为了避免错误的发生,我们需要一些额外的措施。类中的某些方法譬如:银行类的转账方法执行前,可以先记录日志,如果转账失败收款方没有收到钱,我们就根据日志把钱返到付款方账户。在这里,记录日志就是必须要做的操作,银行类的其它方法执行前通常也需要记录日志。
记录日志其实可看作是对转账等方法的增强,事实上,我们就可以通过动态代理对方法增强实现这种功能。
spring的AOP正是基于动态代理来解决上述问题的。
导包
使用spring的aop需要下面这个jar包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
public interface IAccountService {
//模拟保存账户
void saveAccount();
//模拟更新账户
void updateAccount(int i);
//模拟删除账户
int deleteAccount();
}
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("执行类保存");
}
public void updateAccount(int i) {
System.out.println("执行了更新"+i);
}
public int deleteAccount() {
System.out.println("执行了删除");
return 0;
}
}
配置AOP
首先配置AOP的版本信息,要有xmlns:aop,这和之前的不一样。
1、把通知Bean也交给spring来管理
2、使用aop:config标签表明开始AOP的配置
3、使用aop:aspect标签表明配置切面
4、在aop:aspect标签的内部使用对应标签来配置通知的类型我们现在示例是让printLog方法在切入点方法执行之前之前:所以是前置通知
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<!-- 配置Logger类 -->
<bean id="logger" class="com.itheima.utils.Logger"></bean>
<!--配置AOP-->
<aop:config>
<!--配置切面 -->
<aop:aspect id="logAdvice" ref="logger">
<!-- 配置通知的类型,并且建立通知方法和切入点方法的关联-->
<aop:before method="printLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
切入点表达式的写法:
关键字:execution(表达式)
表达式:
访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)标准的表达式写法:
public void com.itheima.service.impl.AccountServiceImpl.saveAccount()