SpringBoot获取ServletContext和webApplicationConnect几种方法

来源:互联网 发布:赛睿淘宝旗舰店 编辑:程序博客网 时间:2024/06/09 20:58

获取ServletContext 的几种方法:

  • 通过HttpServletRequest request获取
ServletContext sc = request.getServletContext();
  • 通过自动注入获取,该方法可以在@Controller下使用,暂未在Service中测试
    @Autowired    private ServletContext servletContext;
  • 通过WebApplicationContext获取
 ServletContext servletContext = webApplicationConnect.getServletContext();

在SpringBoot中,通过ContextLoader获取的方法

  • 目前失效。
  WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
  • 可以通过自动注入
  @Autowired    WebApplicationContext webApplicationConnect;

或者通过实现ApplicationContextAware
实现该接口的setApplicationContext可以注入ApplicationContext 。

可以通过@Component注入到spring中,然后在启动服务时,setApplicationContext会注入参数

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

获取到ApplicationContext后,可以通过getBean的方法 获取到bean工厂中的bean。

@Componentpublic class SpringBeanTool implements ApplicationContextAware {    /**     * 上下文对象实例     */    private ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.applicationContext = applicationContext;    }    /**     * 获取applicationContext     * @return     */    public ApplicationContext getApplicationContext() {        return applicationContext;    }    /**     * 通过name获取 Bean.     * @param name     * @return     */    public Object getBean(String name){        return getApplicationContext().getBean(name);    }    /**     * 通过class获取Bean.     * @param clazz     * @param <T>     * @return     */    public <T> T getBean(Class<T> clazz){        return getApplicationContext().getBean(clazz);    }    /**     * 通过name,以及Clazz返回指定的Bean     * @param name     * @param clazz     * @param <T>     * @return     */    public <T> T getBean(String name,Class<T> clazz){        Assert.hasText(name,"name为空");        return getApplicationContext().getBean(name, clazz);    }}

Assert.hasText(name,”name为空”);这个是属于spring的一个断言类工具。
@Component该注解不能省略。

在Controller中使用时,就通过@Autowired注入即可。

  @Autowired    SpringBeanTool springBeanTool;

方法中使用

   UserService userService1 = springBeanTool.getBean("userService", UserService.class);
原创粉丝点击