获取spring容器上下文

一、servlet 容器 通过WebApplicationContextUtils获取

    //request必须通过servlet的web请求获取
    WebApplicationContext webApp = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

二、通过实现ApplicationContextAware或继承ApplicationObjectSupport(该类实现ApplicationContextAware接口)获取,必须通过spring管理注入

@Configuration
class SpringAppContext implements ApplicationContextAware {
    protected static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }

    public static <T> T getBean(String name, Class<T> beanClass) {
        return context.getBean(name, beanClass);
    }
}
posted @ 2021-04-13 11:20  复一日  阅读(171)  评论(0编辑  收藏  举报