First create a class called AppContextManager like
below:
@Component
public class AppContextManager implements ApplicationContextAware{
private static ApplicationContext _appCtx;
@Override
public void setApplicationContext(ApplicationContext ctx){
_appCtx = ctx;
}
public static ApplicationContext getAppContext(){
return _appCtx;
}
}
Annotate the above class with @Component or
declare a bean for AppContextManager in your application
context xml.
Now in your non-singleton non-spring instance
use the following code snippet to obtain any other spring bean:
ApplicationContext ctx = ApplicationContextManager.getAppContext();
SomeSpringBean bean = ctx.getBean(SomeSpringBean.class);
And this would give you the bean instance anywhere in your code.
本文介绍了一种通过自定义上下文管理器(AppContextManager)在非Spring环境中获取Spring Bean实例的方法。该方法首先创建一个实现了ApplicationContextAware接口的组件,然后通过静态方法提供对ApplicationContext的访问,从而可以在项目的任何地方获取所需的Spring Bean。
408

被折叠的 条评论
为什么被折叠?



