ofbiz实体引擎(二) delegator实例化具体方式

时间:2022-05-03
本文章向大家介绍ofbiz实体引擎(二) delegator实例化具体方式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
/**
     * @author 郑小康
     * 采用spi创建对应实例DelegatorFactoryImpl
     * */
    public static <A, R> R getObjectFromFactory(Class<? extends Factory<R, A>> factoryInterface, A obj) throws ClassNotFoundException {
        Iterator<? extends Factory<R, A>> it = ServiceLoader.load(factoryInterface).iterator();
        while (it.hasNext()) {
            Factory<R, A> factory = it.next();
            R instance = factory.getInstance(obj);
            if (instance != null) {
                return instance;
            }
        }
        throw new ClassNotFoundException(factoryInterface.getClass().getName());
    }

注:上下代码不是在一个类

/**
 * @author 郑小康
 * 根据delegatorName创建一个GenericDelegator
 * 所以实际delegator引用的是一个GenericDelegator实例
 * */
public class DelegatorFactoryImpl extends DelegatorFactory {

    public static final String module = DelegatorFactoryImpl.class.getName();

    public Delegator getInstance(String delegatorName) {
        if (Debug.infoOn()) Debug.logInfo("Creating new delegator [" + delegatorName + "] (" + Thread.currentThread().getName() + ")", module);
        //Debug.logInfo(new Exception(), "Showing stack where new delegator is being created...", module);
        try {
            return new GenericDelegator(delegatorName);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error creating delegator", module);
            return null;
        }
    }
}