java 动态代理的两种实现方式_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java 动态代理的两种实现方式

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

 2012/10/15 10:38:12  tvzic  程序员俱乐部  我要评论(0)
  • 摘要:java动态代理的两种实现方式,jdk代理和cglib的代理方式,示例代码:1.UserService.javapublicinterfaceUserService{publicvoidupdate();}2.UserServiceImpl.javapublicclassUserServiceImplimplementsUserService{privateStringuser=null;publicUserServiceImpl(){}publicUserServiceImpl
  • 标签:实现 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的方式来创建。
发表评论
用户名: 匿名