今天在做一个quartz定时任务的时候,要获取servletContext。想的是获取到request也可以,但这个定时任务不会发起请求,是定时从数据库查数据,所以request不符合场景。然后就想到了servletContext。但是在过程中用了很多种方式都获取不到。因为是在普通类,没有controller这种request。
网上的其他方式配置:
1.servletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
这种不行,不知道是不是版本问题,目前已失效。
2.在web.xml里面配置
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
然后获取,也不可行,不需要另行配置xml,因为使用的spring boot
解决办法:
package com.pinyu.system.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author ypp 创建时间:2018年10月17日 上午11:59:11
* @Description: TODO(用一句话描述该文件做什么)
*/
@Component
@WebListener
public class SpringBeanTool implements ApplicationContextAware, ServletContextListener {
/**
* 上下文对象实例
*/
private ApplicationContext applicationContext;
private ServletContext servletContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取servletContext
*
* @return
*/
public ServletContext getServletContext() {
return servletContext;
}
/**
* 通过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);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
this.servletContext = sce.getServletContext();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
这样其他地方照样可以直接注入随时获取使用
一个是实现了监听器在监听器初始化的时候获取ServletContext ,一个是spring初始化的时候获取ApplicationContext
当然也可以只实现监听器就可以的。也可以获取到ApplicationContext,spring早就为我们写好了,WebApplicationContextUtils.getRequiredWebApplicationContext();
看源码:
获取到的是WebApplicationContext,WebApplicationContext继承ApplicationContext