public class ProxyFactory { public static Object getAgent(Service target,Aop aop) { return Proxy.newProxyInstance( //类加载器 target.getClass().getClassLoader(), //目标对象实现的所有接口 target.getClass().getInterfaces(), //代理功能的实现 new InvocationHandler() { @Override public Object invoke( //生成的代理对象 Object proxy, //正在调用的目标方法 Method method, //目标方法的参数 Object[] args ) throws Throwable { aop.before(); Object invoke = method.invoke(target,args); aop.afeart(); return invoke; } } ); } }
public interface Aop { default void before(){}; default void afeart(){}; default void end(){}; }
public class logAop implements Aop{ @Override public void before() { System.out.println("日志开启"); Aop.super.before(); } }
public class TranAop implements Aop{ @Override public void before() { System.out.println("事物开启"); Aop.super.before(); } @Override public void afeart() { System.out.println("事物进行"); Aop.super.afeart(); } @Override public void end() { System.out.println("事物关闭"); Aop.super.end(); } }
public interface Service { void buy(); }
public interface Service { void buy(); }
public class buyBook implements Service { @Override public void buy() { System.out.println("buy BOOK"); } }
public class buyShop implements Service { @Override public void buy() { System.out.println("buy shop"); } }