在做项目的时候,往往有很多情况是会在非Spring的容器下需要用到Spring管理的组件的,比如说:定时器,servlet,拦截器等等,在这种情况下通常都想使用数据库操作的时候都会感觉到乏力,因为在这种环境下,你要调用相关的Dao层的东西,往往想用依赖注入来实现,卻每每跑出来的就都是空指针异常.
举个例子说明:
public class TaskManager implements ServletContextListener {
// 每天的毫秒数
public static final long DAY = 86400000;
// 定时器
private Timer timer;
// @Autowired
// private GamesetTask gamesetTask;
/**
* 在Web应用结束时停止任务
*/
public void contextDestroyed(ServletContextEvent sce) {
timer.cancel();// 定时器销毁
}
/**
* 在Web应用启动时初始化任务
*/
public void contextInitialized(ServletContextEvent sce) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
// 定义定时器
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
timer = new Timer(true);
GamesetTask gamesetTask = new GamesetTask();// 定时执行的内容
// timer.schedule(locationTask, c.getTime(), DAY); //定时器在每日凌晨0点执行
timer.schedule(gamesetTask, 5000, 4 * 60 * 1000); // 启动后5秒执行,后每隔1小时在执行
// timer.schedule(gamesetTask, 5000, 5 * 1000);
}
}具体的任务如下:
package com.smartsoft.task;
import java.util.Date;
import java.util.TimerTask;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.smartsoft.common.Constants;
import com.smartsoft.dao.GamesetDao;
import com.smartsoft.service.GamesetService;
@Component("gamesetTask")
public class GamesetTask extends TimerTask {
private static boolean isRunning = false;
private static int t = 1 ;
private static int i = 1 ;
@Autowired
private GamesetService gamesetService;
@Autowired
private GamesetDao gamesetDao;
public GamesetTask() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
@Override
public void run() {
if (!isRunning) {
isRunning = true;
System.out.println("-----ganmeset add-------");
addGemest();
isRunning = false;
} else {
System.out.println("-----ganmeset error-------");
}
}
private void addGemest() {
if(t==1){
System.out.println("---------request:newGameSet-------------");
sendHttpRequest("{\"api_key\":\"test"+i+"\",\"table_no\":\"A001\",\"computer_name\":\"computer001\",\"game_set\":\""+i+"\",\"shoe_of_the_day\":\""+i+"\",\"game_time\":\""+new Date()+"\",\"status\":\"1\"}", "http://127.0.0.1:8080/bdb/gameset!newGameSet", Constants.HTTP_CONTENT_TYPE_APPLICATION_JSON);
}else{
int ttt = RandomUtils.nextInt(3);
String res = "";
if(ttt==0){
res = "T";
}else if(ttt==1){
res = "B";
}else{
res = "P";
}
System.out.println("---------request:submitGameResult-------------");
sendHttpRequest("{\"api_key\":\"test"+i+"\",\"table_no\":\"A001\",\"computer_name\":\"computer001\",\"game_set\":\""+i+"\",\"shoe_of_the_day\":\""+i+"\",\"game_time\":\""+new Date()+"\",\"game_no\":\""+i+"\",\"active_game_no\":\""+i+"\",\"win\":\""+res+"\",\"win_type\":\"\",\"banker_pair\":\""+RandomUtils.nextInt(2)+"\",\"player_pair\":\""+RandomUtils.nextInt(2)+"\",\"status\":\"1\"}", "http://127.0.0.1:8080/bdb/gameset!submitGameResult", Constants.HTTP_CONTENT_TYPE_APPLICATION_JSON);
i++;
System.out.println("---------request:newGameSet-------------");
sendHttpRequest("{\"api_key\":\"test"+i+"\",\"table_no\":\"A001\",\"computer_name\":\"computer001\",\"game_set\":\""+i+"\",\"shoe_of_the_day\":\""+i+"\",\"game_time\":\""+new Date()+"\",\"status\":\"1\"}", "http://127.0.0.1:8080/bdb/gameset!newGameSet", Constants.HTTP_CONTENT_TYPE_APPLICATION_JSON);
}
t++;
}
/**
* httpClient
* @param reqStr
* @param urlConfig
* @param contentType
* @return
*/
private int sendHttpRequest(String reqStr,String urlConfig,String contentType) {
try {
PostMethod postMethod = new PostMethod(urlConfig);
RequestEntity requestEntity = new StringRequestEntity(reqStr,contentType,Constants.CONTENT_ENCODING_UTF8);
postMethod.setRequestEntity(requestEntity);
HttpClient httpClient = new HttpClient();
httpClient.executeMethod(postMethod);
JsonResultModel jsonResult=(JsonResultModel)JSONObject.toBean(JSONObject.fromObject(postMethod.getResponseBodyAsString()),JsonResultModel.class);
int httpStatus = Integer.parseInt(jsonResult.getStatus());
return httpStatus;
} catch (Exception e) {
return 500;
}
}
public static void main(String[] args) {
//随机数0或1
for (int i = 0; i < 50; i++) {
System.out.println(RandomUtils.nextInt(2));
}
}
}
@Autowired private GamesetService gamesetService; @Autowired private GamesetDao gamesetDao;
办法很多
网上有人公布怎么获取ioc上下文的,这个也很好明白,但是代码量就比较多,如果有兴趣了解,可以度娘关键字"Web项目中获取SpringBean"
这里我的写法是引入
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);这是Spring的自动装备,有了他前面的注解就不会空指针了,而且代码也美观,整洁
如果有什么不懂,大家可以留言或者问下度娘咯,反正我也是问度娘多
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/qq183293/article/details/47420823