重复造轮子--IOC容器的AOP简单实现

来源:未知 责任编辑:责任编辑 发表时间:2013-12-22 14:54 点击:

之前给大家写过一个简单的IOC容器,这个AOP功能就是在这个上面添加的
 写 Intercept 类 继承 InvocationHandler
public class Intercept implements InvocationHandler{
/**
     * 要处理的对象(也就是我们要在方法的前后加上业务逻辑的对象,如例子中的Hello)
     */
private Object target; // 被代理的目标对象
/**
 *  动态生成方法被处理过后的对象 (写法固定)
 *  target(需要关注的类方法)
 */
public Object bind(Object target) throws InstantiationException, IllegalAccessException
{
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 {
Object result;
AOPModel model=null;
if(InterceptList.getInterceptMethod().containsKey(method.getName()))
{
model=InterceptList.getInterceptMethod().get(method.getName());
this.monitor(model.getBefore(), model.getBefore_aspectName(),this.target);
result = method.invoke(this.target, args);
this.monitor(model.getAfter(), model.getAfter_aspectName(),this.target);
}else {
result = method.invoke(this.target, args);
}
return result;
}
/**
     * 依据是否注入横切关注点来决定before、after的调用
     */
    private void monitor(Object clazz, String aspectName,Object target) throws Exception {
        if (clazz != null) {
            Method[] methods = clazz.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(aspectName)) {
                method.invoke(clazz,target);
                }
            }
        }
    }
   
}

 然后修改我们的IOC容器:当用户继承IOC容器后,自动查找用户配置的参数进行初始化

注意,此时使用this,new Intercept().bind()Load对象


public class IOC {
public IOC()
{
Init();
}
public void Init()
{
Field[] fields = getClass().getDeclaredFields();
for(Field field : fields){
Inject inject=field.getAnnotation(Inject.class);
try {
if(inject!=null)
{
field.setAccessible(true);
if(inject.Intercept())
{
field.set(this,new Intercept().bind(Class.forName(inject.ClassName().trim()).newInstance()));

相关新闻>>

    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • Lexical or Preprocessor Issue 'xxx.h
    • ios学习笔记(二)xcode 4.3.2下实现基本交互
    • ios版本的helloworld
    • iphone(object-c) 内存管理(3) 有效的内存管理 前半部分
    • ios学习笔记(一)xcode 4.3.2下创建第一个ios项目
    • IOS类似iphone通讯录TableView的完整demo【附源码】
    • UITableView一些方法
    • [iPhone中级]iPhone团购信息客户端的开发 (二)
    • 如何为Iphone应用创建启动界面
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1