一、使用jdk自带的动态代理机制:
- 定义一个普通的接口及实现类;
- 定义一个InvocationHandler的实现类用于织入横向插入的操作(此处为打印信息);
- 生成接口的代理类;
- 调用接口方法,实现动态代理。
-
package aopdemo.jdk; public interface INormalService { public void service(); }
package aopdemo.jdk; public class NormalServiceImpl implements INormalService { @Override public void service() { System.out.println("invoke service"); } }
package aopdemo.jdk; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before service"); Object object = method.invoke(target, args); System.out.println("after service"); return object; } }
package aopdemo.jdk; import java.lang.reflect.Proxy; public class JdkProxyDemo { public static void main(String[] args) { INormalService normalService = new NormalServiceImpl(); MyInvocationHandler handler = new MyInvocationHandler(normalService); INormalService iNormalService = (INormalService) Proxy .newProxyInstance(normalService.getClass().getClassLoader(), normalService.getClass().getInterfaces(), handler); iNormalService.service(); } }
执行结果为:
- before service
invoke service
after service
原文地址:https://www.cnblogs.com/silenceshining/p/11129688.html
时间: 2024-10-10 15:08:26