前言:所有demo都是基于maven!所有知识点都有demo代码做案例!
为什么用springAop
因为springAop为业务模块所共同调用的逻辑封装起来,便于减少系统的重复代码,降低模块之间的耦合度,增加系统的可维护性。
快速入门案例
定义一个接口
package com.test;
public interface Student {
public void saveStudent();
}
实现接口
package com.test;
public class StudentImpl implements Student {
public void saveStudent() {
System.out.println("save student");
}
}
定义一个切面
package com.test;
//切面
public class Aspect {
public void begincommit(){
System.out.println("before commit");
}
}
xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="student" class="com.test.StudentImpl"></bean>
<bean id="aspect" class="com.test.Aspect"></bean>
<aop:config>
<!-- 切入点表达式 确定目标类 -->
<aop:pointcut expression="execution(* com.test.StudentImpl.*(..))" id="perform"/>
<!-- ref指向的对象就是切面-->
<aop:aspect ref="aspect">
<aop:before method="begincommit" pointcut-ref="perform"/>
</aop:aspect>
</aop:config>
</beans>
测试类
package com.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AspectTest {
@Test
public void testAspect(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student)context.getBean("student");
student.saveStudent();
}
}
测试运行结果
简单讲解
从例子上可以看出我们仅仅调用了student.saveStudent()这个方法,控制台缺打印出了”before commit”这个东西。如果没有srpingaop我们要在saveStudent之前要调用某一个类,必须得写一个工具类去调用。有了springaop之后我们不需要自己去调用,只需要在配置文件配置下就可以。程序中如果有需要共同调用的模块,就可以定义一个切面,统一调用,代码耦合度就低了不少。例子仅仅用了”前置通知”做案例,如有兴趣继续掌握请看下面知识扩充!
知识扩充
springAop各种通知
前置通知(before):在目标方法执行之前执行
后置通知(after):在目标方执行完成后执行,如果目标方法异常,则后置通知不再执行
异常通知(After-throwing):目标方法抛出异常的时候执行
最终通知(finally);不管目标方法是否有异常都会执行,相当于try…..catch….finally中的finally
环绕通知(round):可以控制目标方法是否执行
重点掌握前置通知、后置通知与环绕通知的区别。
下面会有代码连接,具体请运行代码示例。
springAop注解形式
springAop目前支持两种实现方式,一个是基于xml实现,一个是基于注解方式实现,下面会有代码连接,具体请参考代码示例。
springAop实现原理
springAop底层实现原理是基于jdk动态代理、与cglib动态代理实现,这个我没写demo。
有兴趣可以看这个博客,讲得就挺简洁易懂的,地址:https://blog.csdn.net/qq_27093465/article/details/53340513