代理模式-cglib动态代理

首先创建被代理类的接口

public interface UserService {
    public void add();
    public void delete(int id);

}

接口的实现类

public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("This is add service");
    }

    public void delete(int id) {
        System.out.println("This is delete service:delete " + id );
    }
}

cglib代理拦截器

public class MyMethodInterceptor implements MethodInterceptor {

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("BEFORE METHOD: "+method);
        Object object=methodProxy.invokeSuper(o,objects);
        System.out.println("AFTER METHOD: "+method);
        return object;
    }
}

代理实现及测试

public class TestCglib {
    public static void main(String[] args) {
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(UserServiceImpl.class);
        enhancer.setCallback(new MyMethodInterceptor());
        UserServiceImpl userService= (UserServiceImpl) enhancer.create();

        System.out.println(userService.getClass().getName());
        userService.add();
        System.out.println(" ");
        userService.delete(1);
    }
}

你可能感兴趣的:(Java)