【发布时间】:2021-08-29 10:11:12
【问题描述】:
我们可以使用下面函数的 getBean 方法从非 spring 管理的类中访问 spring 管理的 bean。我想做同样的事情,但在 Kotlin 中。如何在 kotlin 中重写 getBeans 函数以使其工作?
@Component
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext context;
/**
* Returns the Spring managed bean instance of the given class type if it exists.
* Returns null otherwise.
* @param beanClass
* @return
*/
public static <T extends Object> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
// store ApplicationContext reference to access required beans later on
SpringContext.context = context;
}
}
我尝试在 kotlin 中转换它,但出现错误。
@Component
class SpringContext : ApplicationContextAware {
@Throws(BeansException::class)
override fun setApplicationContext(context: ApplicationContext) {
// store ApplicationContext reference to access required beans later on
SpringContext.Companion.context = context
}
companion object {
private var context: ApplicationContext? = null
fun <T : Any>getBean(beanClass: KClass<out T>): Any {
return context!!.getBean(beanClass)
}
}
}
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.lang.Object' available: more than one 'primary' bean found among candidates: [org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.annotation.internalPersistenceAnnotationProcessor, org.springframework.context.event.internalEventListenerProcessor, org.springframework.context.event.internalEventListenerFactory....]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.determinePrimaryCandidate(DefaultListableBeanFactory.java:1591)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1188)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:420)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:350)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1133)
beanClass 变量不知何故得到了 java.lang.Object。为什么会发生这种情况,我该如何解决?
【问题讨论】:
标签: spring spring-boot kotlin