jdk proxy 和 cglib 都可以用来创建动态代理,使用jdk原生的proxy创建代理 被代理对象必须实现某个接口,才能创建代理对象 。 而cglib则没有这个限制 。spring 的 AOP编程中使用了这两种创建动态代理的方法。默认情况下 当某个类实现了接口时使用jdk proxy创建代理 否则使用cglib方式创建代理。
下面是使用jdk proxy创建代理
接口类
public interface UserDao {
public void addUser(String str);
}
实现类
public class UserDaoImpl implements UserDao {
@Override
public void addUser(String str) {
System.out.println(str+"正在添加用户........ "+this.getClass());
}
}
代理工厂类
public class UserProxyFactory implements InvocationHandler
{
private UserDao userDao;
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("添加开始");//方法调用前的业务逻辑
Object o = method.invoke(userDao, args);
System.out.println("添加结束");//调用后的业务逻辑
return o;
}
public UserDao getProxy(UserDao userDao)
{
this.userDao = userDao;
return (UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(), this);
}
public static void main(String[] args)
{
UserDao userDao = new UserDaoImpl();
UserProxyFactory factory = new UserProxyFactory();
UserDao proxy = factory.getProxy(userDao);
proxy.addUser("hello proxy");
proxy.getClass();
}
}
执行输出
添加开始
hello proxy正在添加用户........
添加结束
接下来是cglib创建动态代理
public class CgLibProxyFactory implements MethodInterceptor
{
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy proxyMethod) throws Throwable {
Object o = null;
System.out.println("添加开始....");
o = proxyMethod.invokeSuper(proxy, args);
System.out.println("添加结束....");
return o;
}
public Object getProxy(Object target)
{
Enhancer e = new Enhancer();
e.setSuperclass(target.getClass());
e.setCallback(this);
return e.create();
}
public static void main(String[] args)
{
UserDaoImpl userDaoImpl = new UserDaoImpl();
CgLibProxyFactory proxyFactory = new CgLibProxyFactory();
UserDaoImpl userDaoProxy = (UserDaoImpl)proxyFactory.getProxy(userDaoImpl);
userDaoProxy.addUser("hello cglib");
userDaoProxy.getClass();
}
}
执行输出
添加开始....
hello cglib正在添加用户........