Spring中AOP:Proxy动态代理浅解析(被代理对象必须实现接口)
Posted 呦,你是个老母猪呦!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring中AOP:Proxy动态代理浅解析(被代理对象必须实现接口)相关的知识,希望对你有一定的参考价值。
小贴士:以下内容纯属个人观点,如有不当请指出并谅解
import java.lang.reflect.Proxy;
Proxy可以动态代理一个对象
写一个代理工厂类ProxyFactory:
package com.zhangpn.serviceImpl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory implements InvocationHandler { private Object target;//这是被动态代理的对象 public Object createProxyIntance(Object target) {//通过调用此方法,将被代理目标传入并且返回代理对象,在此invoke方法会被回调 this.target = target; return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("******调用动态被代理对象之前做相关处理******"); method.invoke(target, args); System.out.println("------调用动态被代理对象之后做相关处理------\\n"); return null; } }
写两个被代理类:
第一个User:
package com.zhangpn.daoImpl; import com.zhangpn.dao.UserDao; public class UserDaoImpl implements UserDao { public void save() { System.out.println("UserDaoImpl save success!"); } }
其实现的接口:
package com.zhangpn.dao; public interface UserDao { public void save(); }
第二个Student:
package com.zhangpn.daoImpl; import com.zhangpn.dao.StudentDao; public class StudentDaoImpl implements StudentDao { public void save() { System.out.println("StrudentDaoImpl save success!"); } }
其实现的接口:
package com.zhangpn.dao; public interface StudentDao { public void save(); }
测试运行:
package com.zhangpn.Test; import com.zhangpn.dao.StudentDao; import com.zhangpn.dao.UserDao; import com.zhangpn.daoImpl.StudentDaoImpl; import com.zhangpn.daoImpl.UserDaoImpl; import com.zhangpn.serviceImpl.ProxyFactory; public class Test { public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(); UserDao userDao = (UserDao) factory.createProxyIntance(new UserDaoImpl()); userDao.save(); StudentDao studentDao = (StudentDao) factory.createProxyIntance(new StudentDaoImpl()); studentDao.save(); } }
以上是关于Spring中AOP:Proxy动态代理浅解析(被代理对象必须实现接口)的主要内容,如果未能解决你的问题,请参考以下文章