打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
java的动态代理模式简单实例
java动态代理模式是一种常用的模式,Spring的AOP原理也是基于此。简单实例步骤如下:
第一:编写接口
package com.service;
public interface UserService {
 public void say();
 public void hello();
}
 
第二:接口的实现类
package com.service.impl;
import com.service.UserService;
public class UserServiceBean implements UserService {
 
 private String name;
 
 public UserServiceBean(){};
 
 public UserServiceBean(String name){
  this.name = name;
 }
 
 public void say() {
  System.out.println("恭喜你来到此地...");
  this.hello();
 }
 public void hello() {
  System.out.println("欢迎您!");
 }
 public String getName() {
  return name;
 }
 
}
第三:代理工厂
package com.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.service.impl.UserServiceBean;
public class UserServiceProxy implements InvocationHandler {
 private Object targetObject;
 public Object createProxyIntance(Object targetObject){
  this.targetObject = targetObject;
  return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
    this.targetObject.getClass().getInterfaces(), this);
 }
 
 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  UserServiceBean bean = (UserServiceBean) this.targetObject;
  Object obj = null;
  if(bean.getName() != null){
   if(bean.getName().equals("wuq")){
    obj = method.invoke(this.targetObject, args);
   }else{
    System.out.println("您没有操作权限!");
   }
  }else{
   System.out.println("您没有操作权限!");
  }
  return obj;
 }
}
第四:测试类
package com.test;
import com.aop.UserServiceProxy;
import com.service.UserService;
import com.service.impl.UserServiceBean;
public class UserServiceTest {
 public static void main(String[] args) {
  UserServiceProxy pro = new UserServiceProxy();
  UserServiceBean bean = new UserServiceBean("wuq");
  UserService se = (UserService) pro.createProxyIntance(bean);
  se.say(); 
 }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Spring边学习边总结
Java动态代理的两种实现方法
aspectJ
Spring-AOP核心
Java-06:动态代理
Spring之FactoryBean
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服