AOP(面向方面编程)
作用:不修改源码的情况下对程序进行增强,可以进行权限校验,日志记录等
AOP底层用到的两种代理机制:
JDK 的动态代理 :针对实现了接口的类产生代理.
Cglib 的动态代理 :针对没有实现接口的类产生代理. 应用的是底层的字节码增强的技术
生成当前类的子类对象.(了解)
动态代理
public class LogInterceptor implements InvocationHandler {
/**
* 被代理的对象
*/
@Getter
@Setter
private Object target;
private void before(Method method) {
System.out.println(method.getName()+"调用之前");
}
private void after(Method method) {
System.out.println(method.getName()+"调用之后");
}
/**
* @param proxy 代理的对象
* @param method 代理的方法
* @param args 方法的参数
* @return 方法的返回值
* @throws Throwable 异常
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 前置操作
before(method);
// 通过被代理对象调用真正需要执行的方法
Object res = method.invoke(target, args);
// 后置操作
after(method);
return res;
}
}
测试
@Test
public void proxy() {
// 创建真实的对象
IUserDao userDao = new UserDaoImpl();
// 创建代理
LogInterceptor logInterceptor = new LogInterceptor();
// 设置需要代理的对象
logInterceptor.setTarget(userDao);
// 创建代理之后的对象
/* (关键点)
第一个参数: 真实对象的类解析器
第二个参数: 实现的接口数组
第三个参数: 调用代理方法的时候,会将方法分配给该参数
*/
IUserDao userDaoProxy = (IUserDao) Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
new Class[]{IUserDao.class}, logInterceptor);
userDaoProxy.insert(null);
}
AOP术语
• Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点.
• Advice(通知/增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知.通知分为前置通知,后置 通知,异常通知,最终通知,环绕通知(切面要完成的功能)
• Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
• Introduction(引介):引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类 动态地添加一些方法或 Field. (用处少)
• Target(目标对象): 代理的目标对象
• Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程,(一整个过程)spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装在期织入
• Proxy(代理):一个类被 AOP 织入增强后,就产生一个结果代理类
• Aspect(切面): 是切入点和通知(引介)的结合
注解方式
1.引入jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 增加了切面 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
2.引入配置文件
1.xml文件引入
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!--开启AOP注解-->
<aop:aspectj-autoproxy />
</beans>
2.通过注解的方式开启切面支持 @EnableAspectJAutoProxy