类需要实现接口
public interface IUserServ {
List<Card> findAllUser();
int deleteUserById(Card user);
int saveUser(Card user);
}
代理类
InvocationHandler 接口是动态代理需要的 在这里 处理invoke方法实现自己的需要
public class LogHandler implements InvocationHandler {
//目标对象
private Object targetObject;
/**
* 创建动态代理类
* @return object(代理类)
*/
public Object createProxy(Object targetObject){
this.targetObject = targetObject;
return Proxy.newProxyInstance(
targetObject.getClass().getClassLoader(),
targetObject.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object obj = null;
try {
beforeLog();
//调用目标对象中方法
obj = method.invoke(targetObject, args);
afterLog();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
//自义定增强方法
private void beforeLog(){
System.out.println("开始执行");
}
private void afterLog(){
System.out.println("执行完毕");
}
}
具体的类
public class UserServImpl implements IUserServ {
public int deleteUserById(Card user) {
System.out.println("******执行删除方法******");
return 0;
}
public List<Card> findAllUser() {
System.out.println("*******执行查询方法*******");
return null;
}
public int saveUser(Card user) {
System.out.println("*******执行添加方法********");
return 0;
}
}
main
public static void main(String[] args) {
//IUserServ iuserServ = new UserServImpl();
//Integer number = iuserServ.saveUser(new Card());
//System.out.println(number);
输出
//*******执行添加方法********
//0
//new 代理对象
LogHandler handler = new LogHandler();
//通过代理对象生成具体的类
IUserServ iuserServ = (IUserServ)handler.createProxy(new UserServImpl());
Integer number = iuserServ.saveUser(new Card());
System.out.println(number);
//输出
//开始执行
//*******执行添加方法********
//执行完毕
//0
}
iuserServ.saveUser(new Card());
invoke(Object proxy, Method method, Object[] args)
proxy 照应 iuserServ
method 照应 saveUser
args 照应 Card