您的位置:首页 > 移动开发 > WebAPP

SpringBoot获取ServletContext和webApplicationConnect几种方法

2017-12-15 15:50 871 查看
获取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。

@Component
public class SpringBeanTool implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationCont
4000
ext;
}
/**
* 获取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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: