proxy代理类 package pidan.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;/** * proxyTest:动态代理类 * proxy:针对接口的 * 媒婆:代理类 * 女方:目标类
package pidan.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * proxyTest:动态代理类 * proxy:针对接口的 * 媒婆:代理类 * 女方:目标类 * */ public class ProxyTest implements InvocationHandler { //目标类 private Object obj; //获取代理类 public Object getProxy(Object _obj){ this.obj=_obj; //System.out.println(obj); //生成一个代理类 //this.getClass().getClassLoader() :代理类的构造器 //obj.getClass().getInterfaces() :目标类的接口 return Proxy.newProxyInstance(this.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); } @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { Object result=null; System.out.println("---开始打开连接---"); result=arg1.invoke(obj, arg2); System.out.println("---关闭连接---"); return result; } }spring Test
package pidan.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pidan.dao.IUserService; import pidan.dao.UserService; public class SpringAopTest { public static void main(String[] args) throws Exception { ApplicationContext context=new ClassPathXmlApplicationContext("spring_application.xml"); IUserService service=context.getBean(IUserService.class); service.add(); service.delete(); } }前置增强
package pidan.aop; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class Before implements MethodBeforeAdvice{ @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("我是前置增强AOP-before"); } }后置增强
package pidan.aop; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterReturning implements AfterReturningAdvice{ @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("我是后置增强aop-afterreturning"); } }