欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-07 15:22:16
...
方法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;
    }
}
相关标签: spring java