要求:被代理的对象必须要实现了接口类
接口:
package DynamicProxySpring;
public interface UserDao {
public void save();
public void update();
public void find();
public void delete();
}
被代理的类:
package DynamicProxySpring;
public class UserDaoImp implements UserDao {
public void save() {
System.out.println("save excute");
}
@Override
public void update() {
// TODO Auto-generated method stub
System.out.println("update excute");
}
@Override
public void find() {
// TODO Auto-generated method stub
System.out.println("find excute");
}
@Override
public void delete() {
// TODO Auto-generated method stub
System.out.println("delete excute");
}
}
代理类:(并且将InvocationalHandler直接加在了该类上)
package DynamicProxySpring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyUerDao implements InvocationHandler {
//将被代理的对象传递进来
private UserDao userDao;
public ProxyUerDao(UserDao userDao) {
this.userDao=userDao;
}
public UserDao createUserDao() {
UserDao userDaoProxy=(UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
userDao.getClass().getInterfaces(), this);
return userDaoProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("save".equals(method.getName())) {
System.out.println("权限校验=============");
return method.invoke(userDao, args);
}
return method.invoke(userDao, args);
// TODO Auto-generated method stub
}
}
测试:
package DynamicProxySpring;
public class Test1 {
public void t() {
}
public static void main(String[] args) {
UserDao userDao=new UserDaoImp();
UserDao proxyUerDao=new ProxyUerDao(userDao).createUserDao();
proxyUerDao.save();
proxyUerDao.update();
proxyUerDao.find();
proxyUerDao.delete();
}
}
结果:
权限校验=============
save excute
update excute
find excute
delete excute