春季自动接线不适用于非春季托管类 [英] spring autowiring not working from a non-spring managed class
问题描述
我有一个通过调用构造函数实例化的类(Class ABC).反过来,ABC类具有使用自动连线注入的辅助类(XYZ类).
I have a class (Class ABC) that's instantiated by calling the constructor. Class ABC in turn has a helper class (Class XYZ) injected using auto-wired.
我们是基于Spring MVC的应用程序,在服务器启动时我看不到任何异常.
Ours is a Spring MVC based application and I don't see any exception while server start-up.
但是我仍然看到XYZ类为空.是因为Spring容器未实例化ABC类吗?
But I still see Class XYZ coming as null. Is it because of the fact that Class ABC is not instantiated by Spring Container?
在这种情况下,如何使用自动接线?
In such scenarios, how do i make use of auto-wiring?
谢谢.
推荐答案
您可以使用这种方式在非spring bean类中使用spring bean
You can use this way to use spring bean in non-spring bean class
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
}
现在您可以通过此方法的getApplicationContext()获取applicationcontext对象.
now you can get the applicationcontext object by getApplicationContext() this method.
从applicationcontext中,您可以像这样获得spring bean对象:
from applicationcontext you can get spring bean objects like this:
ApplicationContext appCtx = ApplicationContextUtils
.getApplicationContext();
String strFromContext = (String) appCtx.getBean(beanName);
这篇关于春季自动接线不适用于非春季托管类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!