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();
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。