1.介绍:AOP:面向切面编程,采取横向抽取机制,取代了传统纵向继承体系重复性代码。
2.AOP实现原理
aop底层将采用代理机制进行实现。
接口 + 实现类:spring采用 jdk 的动态代理Proxy。
实现类:spring 采用 cglib字节码增强。
3.AOP术语
1.target目标类:需要被代理的类。例如:UserService
2. Joinpoint连接点:所谓连接点是指那些可能被拦截到的 方法。例如:所有的方法
3. PointCut切入点:已经被增强的连接点。例如:addUser()
4. advice通知/增强,增强代码。例如:after、before
5. Weaving织入:是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
6. proxy代理类
7. Aspect切面:是切入点pointcut和通知advice的结合
一个线是一个特殊的面。
一个切入点和一个通知,组成成一个特殊的面。
4.spring aop编程
4.1依赖jar包
4.2目标类
public interface UserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
4.3切面类
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("前3");
//手动执行目标方法
Object obj = mi.proceed();
System.out.println("后3");
return obj;
}
}
4.4测试类
@Test
public void demo01(){
String xmlPath = "com/selan/b_factory_bean/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获得代理类
UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
userService.addUser();
userService.updateUser();
userService.deleteUser();
}
4.5spring配置文件
<?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">
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.selan.c_spring_aop.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.selan.c_spring_aop.MyAspect"></bean>
<!-- 3 aop编程 -->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.selan.c_spring_aop.*.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
</aop:config>
</beans>