public class TestCglibProxy { public static void main(String[] args) { UserService userService = new UserServiceImpl(); CglibProxy cglibProxy = new CglibProxy(); Enhancer enhancer = new Enhancer(); //设置父类,因为Cglib是针对指定的类生成一个子类,所以需要指定父类 enhancer.setSuperclass(userService.getClass()); enhancer.setCallback(cglibProxy);// 设置回调 UserService userServiceImpl = (UserService)enhancer.create();//创建并返回代理对象 userServiceImpl.save(); } } class CglibProxy implements MethodInterceptor{ @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("开始"); Object result = methodProxy.invokeSuper(o, objects); System.out.println("结束"); return result; } } interface UserService{ void save(); } class UserServiceImpl implements UserService{ @Override public void save() { System.out.println("save method"); } }