在非Spring容器中使用注入
在做项目的时候,往往有很多情况是会在非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);
}
}
这是个很非同的定时器,目的是在服务启动时定时执行GamesetTask任务
具体的任务如下:
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));
}
}
}
以上是我定制的一个定时任务,用httpClient不断请求本地环境某项目的url地址,虽然这里没有操作任何数据库的代码,然是如果某天需要增加需求,在记录每次任务请求返回的数据请,并保存于数据库,或者更具请求给过做出相应的操作,如发邮件什么的,这种情况多用于检测服务器是否运行正常的情况.既然要操作数据库就会想运用相关的dao进行CRUD,如果单纯的在代码敲这几行:
@Autowired
private GamesetService gamesetService;
@Autowired
private GamesetDao gamesetDao;
那保证是空指针,应为这里没有被Spring容器所管理,自然不会被注入,那么怎么解决的呢?
办法很多
网上有人公布怎么获取ioc上下文的,这个也很好明白,但是代码量就比较多,如果有兴趣了解,可以度娘关键字"Web项目中获取SpringBean"
这里我的写法是引入
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
这是Spring的自动装备,有了他前面的注解就不会空指针了,而且代码也美观,整洁
如果有什么不懂,大家可以留言或者问下度娘咯,反正我也是问度娘多
版权声明:本文为qq183293原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。