Spring AOP
AOP即面向切面编程,是面向对象编程(OOP)的补充。
AOP采取横向抽取机制,将分散在各个方法中的重复代码提取出来,然后在程序编译或运行时,再将这些提取出来的代码应用到需要执行的地方。
Spring AOP 模块提供拦截器来拦截一个应用程序,例如,当执行一个方法时,你可以在方法执行之前或之后添加额外的功能。
Spring AOP代理
JDK动态代理的实现
1.创建接口
public interface UserDao {
public void addUser();
public void deleteUser();
}
2.接口实现类
package com.tf.aop;
public class UserDaoimpl implements UserDao {
public void addUser(){
System.out.println("add user");
}
public void deleteUser(){
System.out.println("delete user");
}
}
3.创建切面类
package com.tf.aop;
public class MyAspect {
public void check_permissions(){
System.out.println("模拟检查权限..");
}
public void log(){
System.out.println("模拟记录日志..");
}
}
4. 代理类
package com.tf.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkProxy implements InvocationHandler {
private UserDao userDao;
public Object createProxy(UserDao userDao){
this.userDao=userDao;
ClassLoader classLoader = JdkProxy.class.getClassLoader();
Class[] clazz = userDao.getClass().getInterfaces();
return Proxy.newProxyInstance(classLoader,clazz,this);
}
public Object invoke(Object proxy, Method method ,Object[] args)throws Exception{
MyAspect myAspect = new MyAspect();
myAspect.check_permissions();
Object obj = method.invoke(userDao,args);
myAspect.log();
return obj;
}
}
5.jdk动态代理测试类
package com.tf.aop;
public class JdkTest {
public static void main(String[] args) {
JdkProxy jdkProxy = new JdkProxy();
UserDao userDao = new UserDaoimpl();
UserDao userDao1 = (UserDao)jdkProxy.createProxy(userDao);
userDao.addUser();
userDao.deleteUser();
}
}
6.结果:
add user
delete user
Process finished with exit code 0
CGLIB代理的实现
1.创建目标类
package com.com.tf.CGLIB;
public class UserDao {
public void addUser(){
System.out.println("add user");
}
public void deleteUser(){
System.out.println("delete user");
}
}
2.创建代理类
package com.com.tf.CGLIB;
import com.tf.aop.MyAspect;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibProxy implements MethodInterceptor {
public Object createProxy(Object target){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)throws Exception{
MyAspect myAspect = new MyAspect();
myAspect.check_permissions();
Object obj = methodProxy.invokeSuper(proxy,args);
myAspect.log();
return obj;
}
}
3.创建CGLIB测试类
package com.com.tf.CGLIB;
public class CglibTest {
public static void main(String[] args) {
CglibProxy cglibProxy = new CglibProxy();
UserDao userDao = new UserDao();
UserDao userDao1 = (UserDao)cglibProxy.createProxy(userDao);
userDao.addUser();
userDao.deleteUser();
}
}
以上是spring AOP的两种不同代理实现,未完待续,咕~