一.spring aop是什么?
spring aop 面向切面编程。业务逻辑层在处理业务之前和之后都要进行一些参数的校验,异常处理,日志记录等代码,有非常多非核心的业务逻辑在里面,这些业务逻辑不要是不行的。怎么解决这种问题?生活中有很多这样的例子,实际上就是使用了代理模式来解决这个问题。spring aop就是基于代理模式的。代理分静态代理和动态代理,spring aop的核心就是通过动态代理来实现的。
二.使用bean的方式配置spring的aop
1.先创建项目,并运行
第一步,创建spring 项目 引入jar包
第二步,创建主配置文件
第三步,创建包实体类
注意 service层只保留核心的业务逻辑代码。
第四步,在spring 的主配置文件中配置bean
第五步,写测试类
2.实现spring的aop
第一步,加入spring aop的jar包

第二步,声明日志处理类的代码 ,在spring aop中,管这种代码叫通知

第三步,在spring的主配置文件中配置aop


第四步,测试
/** * 获取对象 */ public class Test01 { public static void main(String[] args) { //创建spring的工厂类对象 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //从工厂中获取对象 UserService userService = context.getBean(UserService.class); userService.saveUser(new User()); userService.deleteUser(new User()); userService.updateUser(new User()); userService.findById(10L); } }
注意:如果bean对象没有实现接口,使用aop是会报错的。
这个是因为spring aop底层是基于动态代理来实现的,动态代理实现有两种方式:
jdk动态代理
spring 模式使用的是jdk动态搭理,jdk动态代理要求目标类的对象(UserServiceImpl)必须实现一个接口,而且
获取目标类对象的时候要做向上转型为接口。
cglib动态代理
cglib 代理方式spring aop也支持,cglib实现动态代理的时候不需要目标类(UserServiceImpl)实现接口
如果要把spring aop的代理方式改为cglib,需要如下配置:
proxy-target-class如果设置成true使用cglib动态代理,默认是false使用jdk动态代理。
三.spring aop常用的五种通知类型

举例:
环绕通知
第一步,首先要在通知类中声明环绕通知要执行的方法

第二步,在spring主配置文件中配置环绕通知

第三步,运行测试
异常通知
第一步,自定义运行时异常

第二步,模拟抛出自定义的运行时异常

第三步,在通知类中声明发生异常了需要处理的方法

第四步,在spring主配置文件中配置异常通知

第五步,测试