package org.rocfish.dao.impl

import org.rocfish.dao.OptionTarget
import org.rocfish.dao.OptionTargetFactory
import org.springframework.beans.factory.FactoryBean
import org.springframework.beans.factory.NoSuchBeanDefinitionException
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import kotlin.reflect.KClass

/**
 * 使用spring容器实现得optiontarget工厂
 */
open class SpringOptionTargetFactory:OptionTargetFactory, ApplicationContextAware {

    private lateinit var context: ApplicationContext

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        this.context = applicationContext
    }

    override fun <T> getTarget(clazz: KClass<*>): OptionTarget<T> {
        return this.context.getBean(clazz.qualifiedName!!)?.let {
            when (it) {
                is FactoryBean<*> -> it.`object` as OptionTarget<T>
                else -> it as OptionTarget<T>
            }
        }
    }
}