AOP实现起来代码相当简单.主要核心是动态代理和反射.
一.接口类:
public interface MethodDao { public void sayHello(); }二.接口实现类:
public class MethodImpl implements MethodDao { public void sayHello() { System.out.println("hello world"); } }三.编写动态代理类DynamicProxy,***实现InvocationHandler接口
四.编写测试类:
public class Test { public static void main(String[] args) { MethodDao methodDao=new MethodImpl(); InvocationHandler handler = new DynamicProxy(methodDao); //第一个参数是类加载器,与handler相同; //第二个是参数对象实现的接口,如果没有的话需要使用cdlib //第三个参数是InvocationHandler. //该类返回的其实是MethodImpl类 methodDao=(MethodDao) Proxy.newProxyInstance(handler.getClass().getClassLoader(), methodDao.getClass().getInterfaces(), handler); methodDao.sayHello(); } }五.查看控制台输出:
=====方法执行前=======
hello world
=====方法执行后=======
六.总结:
通过上面的代码可以总结出AOP的应用场景:
1.事务管理,(事务的开启跟提交可以直接交由aop来处理,程序员可以更加专注于业务)
2.日志管理(在方法调用的前后可以打印日志)
3.权限管理(比如登录验证.管理员权限等,在调用某个方法时,如果权限不够也可以提示).
以上这篇动态代理模拟实现aop的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。