Java 动态代理

Java动态代理的实现有两种方式:

1、jdk 自带的动态代理

2、spring 中的cglib实现的动态代理

区别:

jdk自带的动态代理一定要有接口interface类,而cglib不需要。

(1)基本信息

UserInfoService.java 类:

public interface UserInfoService {   
    String getUserName(String userName);
}
UserInfoServiceImpl类:
public class UserInfoServiceImpl implements UserInfoService{
    
    @Override
    public String getUserName(String userName) {
        return userName;
    }
}

(2)jdk 自带的动态代理

UserInfoServiceImplJdk.java

public class UserInfoServiceImpJdk implements InvocationHandler {
    
    private Object target;
    
    public Object bind(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;

        System.out.println("jdk proxy before ...");
        result = method.invoke(target, args);
        System.out.println("jdk proxy after ...");
        
        return result;
    }

    public static void main(String[] args) {
        UserInfoServiceImpl userInfoServiceImpl = new UserInfoServiceImpl();
        UserInfoServiceImpJdk userInfoServiceImpJdk = new UserInfoServiceImpJdk();
        UserInfoServiceImpl userInfoServiceImp2 = (UserInfoServiceImpl) userInfoServiceImpJdk.bind(userInfoServiceImpl);
        String result = userInfoServiceImp2.getUserName("tim");
        System.out.println(result);
    }
}

(3) Spring cglib实现的动态代理

public class UserInfoServiceImplCglib implements MethodInterceptor {
    
    private Object target;
    
    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
    
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before cglib ....");
        Object object = methodProxy.invokeSuper(o, objects);
        System.out.println("after");
        return object;
    }

    public static void main(String[] args) {
        UserInfoServiceImpl userInfoService = new UserInfoServiceImpl();
        UserInfoServiceImplCglib userInfoServiceImplCglib = new UserInfoServiceImplCglib();
        UserInfoServiceImpl userInfoService1 = (UserInfoServiceImpl)userInfoServiceImplCglib.getInstance(userInfoService);
        String result = userInfoService1.getUserName("tim");
        System.out.println(result);
    }
}

 

你可能感兴趣的:(Java,Web)