静态代理略过,哈哈
主要来说动态代理
1、jdk实现的动态代理
有两个主要类,一个是Proxy,一个是InvocationHandler
public interface UserService {
public void add();
public void delete();
}
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("执行了add方法");
}
@Override
public void delete() {
System.out.println("执行了delete方法");
}
}
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的真实对象
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
beforeLog(method.getName());
Object result = method.invoke(target, args);
afterLog(method.getName());
return result;
}
public void beforeLog(String methodName){
System.out.println("开始执行【" + methodName + "】方法。");
}
public void afterLog(String methodName){
System.out.println("执行了【" + methodName + "】方法结束。");
}
}
public class Client {
public static void main(String[] args) {
UserServiceImpl userServiceImpl = new UserServiceImpl();
ProxyInvocationHandler invocationHandler = new ProxyInvocationHandler();
invocationHandler.setTarget(userServiceImpl);
UserService proxy = (UserService) invocationHandler.getProxy();
proxy.add();
}
}
输出结果
2、cglib实现的动态代理
引入依赖
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>7.1</version>
</dependency>
public class CglibProxy implements MethodInterceptor{
private Object target;
public Object getInstance(final Object target){
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object object, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
beforeLog(method.getName());
Object result = method.invoke(target, args);
afterLog(method.getName());
return result;
}
public void beforeLog(String methodName){
System.out.println("开始执行【" + methodName + "】方法。");
}
public void afterLog(String methodName){
System.out.println("执行了【" + methodName + "】方法结束。");
}
}
public class Client {
public static void main(String[] args) {
UserServiceImpl userServiceImpl = new UserServiceImpl();
CglibProxy cglibProxy = new CglibProxy();
UserService instance = (UserService) cglibProxy.getInstance(userServiceImpl);
instance.add();
}
}
输出结果