实现jdk动态代理-InvocationHandler(简单易懂)

如果要使用jdk动态代理,目标类必须实现接口

1.接口

public interface PeopleService {

    void eat();
}

2.实现类

public class PeopleServiceImpl implements PeopleService {


    @Override
    public void eat() {
        System.out.println("开始吃饭了.......");
    }
}

3.动态代理类

public class PeopleInvocationHandler implements InvocationHandler {

    /**
     * 代理类中的真实对象
     */
    private final Object target;

    public PeopleInvocationHandler(Object target) {
        this.target = target;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("吃饭之前要做什么....");
        method.invoke(target, args);
        System.out.println("吃饭后要做什么.....");
        return null;
    }
}

3.代理工厂类

public class JdkProxyFactory {


    public static Object getPeopleProxy(Object target) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(), // 目标类的类加载
                target.getClass().getInterfaces(),  // 代理需要实现的接口,可指定多个
                new PeopleInvocationHandler(target)   // 代理对象对应的自定义 InvocationHandler
        );
    }
}

4.测试

@ApiOperation("测试jdk动态代理")
@PostMapping(value = "/test")
public void test() {
    PeopleService proxy = (PeopleService)JdkProxyFactory.getPeopleProxy(new PeopleServiceImpl());
    proxy.eat();
}

5.执行结果

吃饭之前要做什么....
开始吃饭了.......
吃饭后要做什么.....

你可能感兴趣的:(java原创文章,java,spring,boot)