package com.jxd.test.proxy; import com.jxd.test.entity.Order; import com.jxd.test.service.OrderService; import com.jxd.test.service.impl.OrderServiceImpl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JdkMapperProxy implements InvocationHandler { /** * 目标对象 */ private Object target; public JdkMapperProxy(Object target) { this.target = target; } /** * @param proxy 表示代理类 * @param method 表示目标方法 * @param args 表示目标方法参数 * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(">>前置通知.."); System.out.println(">>后置通知.."); return new Order(18,6); } public static void main(String[] args) { OrderService mapper = getMapper(OrderService.class); Order order =mapper.select(); System.out.println(order.getOrderId()); System.out.println(order.getUserId()); } private static <T> T getMapper(Class<T> type) { return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new JdkMapperProxy(type)); } }
order接口无实现类
public interface OrderService { String add(); Order select(); }
Order的实体类 @Data public class Order { private Integer orderId; private Integer userId; public Order() { } public Order(Integer orderId, Integer userId) { this.orderId = orderId; this.userId = userId; } }