Search in sources :

Example 1 with ObjectProxy

use of org.nutz.ioc.ObjectProxy in project nutz by nutzam.

the class AnnotationIocLoaderTest method test_ioc_inject_by_setter.

@Test
public void test_ioc_inject_by_setter() throws ObjectLoadException {
    AnnotationIocLoader loader = new AnnotationIocLoader(getClass().getPackage().getName());
    Logs.get().error(loader.load(null, "issue1060"));
    NutIoc ioc = new NutIoc(loader);
    // 放个假的
    ioc.getIocContext().save("app", "dao", new ObjectProxy(new NutDao()));
    ioc.get(Issue1060.class);
    ioc.depose();
}
Also used : NutIoc(org.nutz.ioc.impl.NutIoc) NutDao(org.nutz.dao.impl.NutDao) ObjectProxy(org.nutz.ioc.ObjectProxy) Test(org.junit.Test)

Example 2 with ObjectProxy

use of org.nutz.ioc.ObjectProxy in project nutz by nutzam.

the class InnerValue method get.

public Object get(IocMaking ing) {
    IocMaking innering = ing.clone(null);
    ObjectProxy op = ing.getObjectMaker().make(innering, iobj);
    return op.get(iobj.getType(), innering);
}
Also used : IocMaking(org.nutz.ioc.IocMaking) ObjectProxy(org.nutz.ioc.ObjectProxy)

Example 3 with ObjectProxy

use of org.nutz.ioc.ObjectProxy in project nutz by nutzam.

the class ScopeJsonIocTest method test_simple_scope.

@Test
public void test_simple_scope() {
    Ioc2 ioc = I(J("f1", "scope:'app',fields:{name:'F1'}"), J("f2", "scope:'MyScope',fields:{name:'F2'}"));
    Animal f1 = ioc.get(Animal.class, "f1");
    assertEquals("F1", f1.getName());
    Animal f2 = ioc.get(Animal.class, "f2");
    assertEquals("F2", f2.getName());
    Animal f22 = ioc.get(Animal.class, "f2");
    assertEquals("F2", f22.getName());
    assertFalse(f2 == f22);
    ScopeContext ic = new ScopeContext("MyScope");
    Map<String, ObjectProxy> map = ic.getObjs();
    f2 = ioc.get(Animal.class, "f2", ic);
    assertEquals("F2", f2.getName());
    f22 = ioc.get(Animal.class, "f2", ic);
    assertEquals("F2", f22.getName());
    assertTrue(f2 == f22);
    assertEquals(1, map.size());
    ioc.get(Animal.class, "f1", ic);
    assertEquals(1, map.size());
}
Also used : ScopeContext(org.nutz.ioc.impl.ScopeContext) Animal(org.nutz.ioc.json.pojo.Animal) Ioc2(org.nutz.ioc.Ioc2) ObjectProxy(org.nutz.ioc.ObjectProxy) Test(org.junit.Test)

Example 4 with ObjectProxy

use of org.nutz.ioc.ObjectProxy in project nutz by nutzam.

the class NutIoc method get.

public <T> T get(Class<T> type, String name, IocContext context) throws IocException {
    if (log.isDebugEnabled())
        log.debugf("Get '%s'<%s>", name, type == null ? "" : type);
    try {
        if (this.mirrors instanceof LifeCycle)
            ((LifeCycle) this.mirrors).init();
    } catch (Exception e) {
        throw new IocException("_mirror_factory_init", e, "Mirror Factory init fail");
    }
    // 创建对象创建时
    IocMaking ing = makeIocMaking(context, name);
    IocContext cntx = ing.getContext();
    // 从上下文缓存中获取对象代理
    ObjectProxy op = cntx.fetch(name);
    // 如果未发现对象
    if (null == op) {
        // 线程同步
        synchronized (lock_get) {
            // 再次读取
            op = cntx.fetch(name);
            // 如果未发现对象
            if (null == op) {
                try {
                    if (log.isDebugEnabled())
                        log.debug("\t >> Load definition name=" + name);
                    // 读取对象定义
                    IocObject iobj = loader.load(createLoading(), name);
                    if (null == iobj) {
                        for (String iocBeanName : loader.getName()) {
                            // 感觉没必要..没有就没有呗
                            if (3 > LevenshteinDistance.computeLevenshteinDistance(name.toLowerCase(), iocBeanName.toLowerCase())) {
                                throw new IocException(name, "Undefined object '%s' but found similar name '%s'", name, iocBeanName);
                            }
                        }
                        throw new IocException(name, "Undefined object '%s'", name);
                    }
                    // 修正对象类型
                    if (null == iobj.getType())
                        if (null == type && Strings.isBlank(iobj.getFactory()))
                            throw new IocException(name, "NULL TYPE object '%s'", name);
                        else
                            iobj.setType(type);
                    // 检查对象级别
                    if (Strings.isBlank(iobj.getScope()))
                        iobj.setScope(defaultScope);
                    // 根据对象定义,创建对象,maker 会自动的缓存对象到 context 中
                    if (log.isDebugEnabled())
                        log.debugf("\t >> Make...'%s'<%s>", name, type == null ? "" : type);
                    op = maker.make(ing, iobj);
                }// 处理异常
                 catch (IocException e) {
                    ((IocException) e).addBeanNames(name);
                    throw e;
                } catch (Throwable e) {
                    throw new IocException(name, e, "For object [%s] - type:[%s]", name, type == null ? "" : type);
                }
            }
        }
    }
    synchronized (lock_get) {
        T re = op.get(type, ing);
        if (!name.startsWith("$") && re instanceof IocLoader) {
            loader.addLoader((IocLoader) re);
        }
        return re;
    }
}
Also used : LifeCycle(org.nutz.lang.util.LifeCycle) IocContext(org.nutz.ioc.IocContext) IocMaking(org.nutz.ioc.IocMaking) IocException(org.nutz.ioc.IocException) IocObject(org.nutz.ioc.meta.IocObject) ComboIocLoader(org.nutz.ioc.loader.combo.ComboIocLoader) IocLoader(org.nutz.ioc.IocLoader) ObjectProxy(org.nutz.ioc.ObjectProxy) IocException(org.nutz.ioc.IocException)

Example 5 with ObjectProxy

use of org.nutz.ioc.ObjectProxy in project nutz by nutzam.

the class ObjectMakerImpl method make.

public ObjectProxy make(final IocMaking ing, IocObject iobj) {
    // 获取 Mirror, AOP 将在这个方法中进行
    Mirror<?> mirror = ing.getMirrors().getMirror(iobj.getType(), ing.getObjectName());
    // 获取配置的对象事件集合
    IocEventSet iocEventSet = iobj.getEvents();
    // 建立对象代理,并保存在上下文环境中 只有对象为 singleton
    // 并且有一个非 null 的名称的时候才会保存
    // 就是说,所有内部对象,将会随这其所附属的对象来保存,而自己不会单独保存
    ObjectProxy op = new ObjectProxy();
    if (iobj.isSingleton() && null != ing.getObjectName())
        ing.getContext().save(iobj.getScope(), ing.getObjectName(), op);
    // 为对象代理设置触发事件
    if (null != iobj.getEvents()) {
        op.setFetch(createTrigger(mirror, iocEventSet.getFetch()));
        op.setDepose(createTrigger(mirror, iocEventSet.getDepose()));
    }
    try {
        // 准备对象的编织方式
        DefaultWeaver dw = new DefaultWeaver();
        op.setWeaver(dw);
        // 为编织器设置事件触发器:创建时
        if (null != iobj.getEvents()) {
            dw.setCreate(createTrigger(mirror, iocEventSet.getCreate()));
        }
        // 构造函数参数
        ValueProxy[] vps = new ValueProxy[Lang.length(iobj.getArgs())];
        for (int i = 0; i < vps.length; i++) vps[i] = ing.makeValue(iobj.getArgs()[i]);
        dw.setArgs(vps);
        // 先获取一遍,根据这个数组来获得构造函数
        Object[] args = new Object[vps.length];
        boolean hasNullArg = false;
        for (int i = 0; i < args.length; i++) {
            args[i] = vps[i].get(ing);
            if (args[i] == null) {
                hasNullArg = true;
            }
        }
        // 缓存构造函数
        if (iobj.getFactory() != null) {
            // factory这属性, 格式应该是 类名#方法名 或者 $iocbean#方法名
            final String[] ss = iobj.getFactory().split("#", 2);
            if (ss[0].startsWith("$")) {
                dw.setBorning(new Borning<Object>() {

                    public Object born(Object... args) {
                        Object factoryBean = ing.getIoc().get(null, ss[0].substring(1));
                        return Mirror.me(factoryBean).invoke(factoryBean, ss[1], args);
                    }
                });
            } else {
                Mirror<?> mi = Mirror.me(Lang.loadClass(ss[0]));
                if (hasNullArg) {
                    Method m = (Method) Lang.first(mi.findMethods(ss[1], args.length));
                    if (m == null)
                        throw new IocException(ing.getObjectName(), "Factory method not found --> ", iobj.getFactory());
                    dw.setBorning(new MethodCastingBorning<Object>(m));
                } else {
                    Method m = mi.findMethod(ss[1], args);
                    dw.setBorning(new MethodBorning<Object>(m));
                }
            }
        } else {
            dw.setBorning((Borning<?>) mirror.getBorning(args));
        }
        // 如果这个对象是容器中的单例,那么就可以生成实例了
        // 这一步非常重要,它解除了字段互相引用的问题
        Object obj = null;
        if (iobj.isSingleton()) {
            obj = dw.born(ing);
            op.setObj(obj);
        }
        // 获得每个字段的注入方式
        List<IocField> _fields = new ArrayList<IocField>(iobj.getFields().values());
        FieldInjector[] fields = new FieldInjector[_fields.size()];
        for (int i = 0; i < fields.length; i++) {
            IocField ifld = _fields.get(i);
            try {
                ValueProxy vp = ing.makeValue(ifld.getValue());
                fields[i] = FieldInjector.create(mirror, ifld.getName(), vp, ifld.isOptional());
            } catch (Exception e) {
                throw Lang.wrapThrow(e, "Fail to eval Injector for field: '%s'", ifld.getName());
            }
        }
        dw.setFields(fields);
        // 如果是单例对象,前面已经生成实例了,在这里需要填充一下它的字段
        if (null != obj)
            dw.fill(ing, obj);
        // 对象创建完毕,如果有 create 事件,调用它
        dw.onCreate(obj);
    } catch (IocException e) {
        ing.getContext().remove(iobj.getScope(), ing.getObjectName());
        ((IocException) e).addBeanNames(ing.getObjectName());
        throw e;
    }// 当异常发生,从 context 里移除 ObjectProxy
     catch (Throwable e) {
        ing.getContext().remove(iobj.getScope(), ing.getObjectName());
        throw new IocException(ing.getObjectName(), e, "throw Exception when creating");
    }
    // 返回
    return op;
}
Also used : IocException(org.nutz.ioc.IocException) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) FieldInjector(org.nutz.ioc.weaver.FieldInjector) IocException(org.nutz.ioc.IocException) DefaultWeaver(org.nutz.ioc.weaver.DefaultWeaver) ValueProxy(org.nutz.ioc.ValueProxy) IocEventSet(org.nutz.ioc.meta.IocEventSet) IocField(org.nutz.ioc.meta.IocField) ObjectProxy(org.nutz.ioc.ObjectProxy) IocObject(org.nutz.ioc.meta.IocObject)

Aggregations

ObjectProxy (org.nutz.ioc.ObjectProxy)8 IocException (org.nutz.ioc.IocException)4 IocObject (org.nutz.ioc.meta.IocObject)4 ArrayList (java.util.ArrayList)3 IocContext (org.nutz.ioc.IocContext)3 Test (org.junit.Test)2 IocMaking (org.nutz.ioc.IocMaking)2 Method (java.lang.reflect.Method)1 Entry (java.util.Map.Entry)1 DataSource (javax.sql.DataSource)1 NutDao (org.nutz.dao.impl.NutDao)1 Ioc2 (org.nutz.ioc.Ioc2)1 IocLoader (org.nutz.ioc.IocLoader)1 ValueProxy (org.nutz.ioc.ValueProxy)1 NutIoc (org.nutz.ioc.impl.NutIoc)1 ScopeContext (org.nutz.ioc.impl.ScopeContext)1 Animal (org.nutz.ioc.json.pojo.Animal)1 ComboIocLoader (org.nutz.ioc.loader.combo.ComboIocLoader)1 IocEventSet (org.nutz.ioc.meta.IocEventSet)1 IocField (org.nutz.ioc.meta.IocField)1