1.JDK动态代理(要有接口)
package com.itheima.util;
//jdk动态代理工厂
public class JDKProxyFactory {
public static Object getProxy(Class clazz){
//生成代理对象
Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new InvocationHandler() {@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Logger logger = new Logger();
Object obj = null;
try {
//前置增强
logger.m1();
//method.invoke:被代理的对象执行方法
obj = method.invoke(clazz.newInstance(), args);
//后置增强
logger.m2();
} catch (Exception e) {
e.printStackTrace();
logger.m3();
}
return obj;
}
});
return proxy;
}
}
package com.itheima.service.impl;
public class DeptServiceImpl implements DeptService {
@Override
public List<Dept> findAll() {
System.out.println("findAll 查询列表");
return new ArrayList<>();
}}
package com.itheima.test;
public class DeptServiceTest {
@Test
public void test1() {
DeptService deptService = (DeptService) JDKProxyFactory.getProxy(DeptServiceImpl.class);
deptService.findAll();
}}
2.Cglib动态代理(被代理对象可以被继承 )
package com.itheima.util;
//Cglib动态代理(基于继承)
public class CglibProxyFactory {
public static Object getProxy(Class clazz){
//创建一个代理工具类
Enhancer enhancer = new Enhancer();//根据父类创建子类对象(认爹)
enhancer.setSuperclass(clazz);//调用代理对象的方法(增强的代码写在这里)
enhancer.setCallback(new InvocationHandler() {
@Override
//参数一:代理对象本身(用不上)
//参数二:代理对象方法
//参数三:方法的参数
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
Logger logger = new Logger();
//前置增强
logger.m1();//执行被代理对象的方法
Object invoke = method.invoke(clazz.newInstance(), objects);//后置增强
logger.m2();//返回方法执行的返回值
return invoke;
}
});//生成代理对象并返回
Object proxy = enhancer.create();
return proxy;
}
}
package com.itheima.service.impl;
public class DeptServiceImpl {
public List<Dept> findAll() {
System.out.println("findAll 查询列表");
return new ArrayList<>();
}
}
package com.itheima.test;
public class DeptServiceTest {
@Test
public void test1() {
DeptServiceImpl deptService = (DeptServiceImpl) CglibProxyFactory.getProxy(DeptServiceImpl.class);
deptService.findAll();
}}