一、Spring AOP是什么
- AOP:面向切面,是一种编程思想,OOP的延续。
- 将系统中非核心的业务提取出来,进行单独处理。比如事务、日志和安全等。这个简单来说就是可以在一段程序之前或者之后做一些事。
二、Spring AOP源码
AOP源码中用到了两种动态代理来实现拦截切入功能:jdk动态代理和cglib动态代理。
(1)jdk动态代理:由java内部的反射机制来实现的。反射机制在生成类的过程中比较高效,但前提是目标类基于统一的接口,如果没有jdk代理不能应用。
/**
** jdk动态代理实现
**/
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
InvocationHandler invocationHandler = new MyInvocationHandler(userService);
//三个参数
//(1)Classloader:类加载器,因为需要生成一个类
//(2)Class<?>[]:我们需要代理对象实现的数组
//(3)InvocationHandler:调用处理器
UserService userServiceProxy = (UserService)Proxy.newProxyInstance(userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(), invocationHandler);
System.out.println(userServiceProxy.getName(1));
System.out.println(userServiceProxy.getAge(1));
}
(2)cglib动态代理:借助asm实现的。asm在生成类之后的相关执行过程比较高效(可以通过将asm生成的类进行缓存,这样解决asm生成类过程低效问题)
public static void main(String[] args) {
//net.sf.cglib.proxy.Enhancer – 主要的增强类
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserServiceImpl.class);
//net.sf.cglib.proxy.MethodInterceptor – 主要的方法拦截类,它是Callback接口的子接口,需要用户实现
enhancer.setCallback(new MethodInterceptor() {
//net.sf.cglib.proxy.MethodProxy – JDK的java.lang.reflect.Method类的代理类,可以方便的实现对源对象方法的调用
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("before method run...");
//实现对原方法的使用,虽然第一个参数是被代理对象,也不会出现死循环的问题。
Object result = proxy.invokeSuper(obj, args);
System.out.println("after method run...");
return result;
}
});
UserService o = (UserService)enhancer.create();
o.getName(1);
o.getAge(1);
}