当前位置: 代码迷 >> Web前端 >> java 动态署理的两种实现方式
  详细解决方案

java 动态署理的两种实现方式

热度:98   发布时间:2012-11-22 00:16:41.0
java 动态代理的两种实现方式
java 动态代理的两种实现方式,jdk代理和cglib的代理方式,示例代码:
1.UserService.java
public interface UserService {
public void update();
}

2.UserServiceImpl.java
public class UserServiceImpl implements UserService {
private String user = null;

public UserServiceImpl() {
}

public UserServiceImpl(String user) {
   this.user = user;
}

public void update() {
   System.out.println("执行更新方法!");
}

public String getUser() {
   return user;
}
}
3.JDKProxyFactory.java
public class JDKProxyFactory implements InvocationHandler {
private Object target;

public Object createProxyInstance(Object target) {
   this.target = target;
   return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   UserServiceImpl userService = (UserServiceImpl) this.target;
   Object object = null;
   if (userService.getUser() != null) {
    object = method.invoke(target, args);
   }
   return object;
}
}

4.CglibProxyFactory.java
public class CglibProxyFactory implements MethodInterceptor {
private Object target;

public Object createProxyInstance(Object target) {
   this.target = target;
   Enhancer enhancer = new Enhancer();
   enhancer.setSuperclass(this.target.getClass());// 非final方法修饰
   enhancer.setCallback(this);
   return enhancer.create();

}

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
   UserServiceImpl userService = (UserServiceImpl) this.target;
   Object object = null;
   if (userService.getUser() != null) {
    object = method.invoke(target, args);
   }
   return object;
}
}

5.JunitAOP.java
public class JunitAOP {
@Test
public void testProxyJdk() throws Exception {
   JDKProxyFactory proxyFactory = new JDKProxyFactory();
   UserService service = (UserService) proxyFactory.createProxyInstance(new UserServiceImpl("xxx"));
   service.update();
}

@Test
public void testProxyCglib() throws Exception {
   CglibProxyFactory proxyFactory = new CglibProxyFactory();
   UserServiceImpl service = (UserServiceImpl) proxyFactory.createProxyInstance(new UserServiceImpl("xxx"));
   service.update();
}
}

注:JDK的Proxy.newProxyInstance()方式创建的代理对象必须实现一个接口,
没有实现接口的类要创建代理必须由cglib的方式来创建。
  相关解决方案