spring 动态代理工具类使用教程

main方法

		ProxyFactory proxyFactory = new ProxyFactory();
        Train train = new Train();
        proxyFactory.setTarget(train);
        DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor();
        defaultPointcutAdvisor.setAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation methodInvocation) throws Throwable {
                String name = methodInvocation.getMethod().getName();
                System.out.println(name);

                System.out.println("befor method train run ...");
                Object proceed = methodInvocation.proceed();
                System.out.println("after method train run ...");
                return proceed;
            }
        });


        proxyFactory.addAdvisor(defaultPointcutAdvisor);


        Train proxy1 = (Train) proxyFactory.getProxy();

        proxy1.move2();

代理目标类

public class Train {
    public void move() {
        System.out.println("火车行驶中");
    }
    public void move2() {
        System.out.println("火车2行驶中");
    }

}

你可能感兴趣的:(每天进步一点,spring,java,后端)