spring 自动装配在非 spring 托管类中不起作用 [英] spring autowiring not working from a non-spring managed 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 Container没有实例化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
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext appContext) {
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 = appCtx.getBean(beanName, String.class);
这篇关于spring 自动装配在非 spring 托管类中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!