`
yixiandave
  • 浏览: 138729 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Spring应用内部获取ApplicationContext的两种方法

阅读更多
方法1:
继承ApplicationObjectSupport类,然后调用继承的方法手动获取:
ConfigurableApplicationContext context = (ConfigurableApplicationContext) getApplicationContext();
//动态添加新的bean

接下来就可以做想做的事了

方法2:
实现ApplicationContextAware接口,重写setApplicationContext方法,Spring会创建bean时自动注入
完整案例
@Controller
@RequestMapping("/test")
public class SessionTestController implements ApplicationContextAware {
    private ExcelCache prevCache;
    private ApplicationContext applicationContext;

    @RequestMapping("/testsessionscope")
    public @ResponseBody
    JSONObject testSessionScope(){
        JSONObject res = new JSONObject();
        ExcelCache excelCache = getExcelCache();
//do something
        return res;
    }


    private ExcelCache getExcelCache() {
        return (ExcelCache) applicationContext.getBean("excelCache");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics