在定时器中service注入不进去的解决方案

定时器首先要继承ServletContextListener,然后实现里面的方法
contextDestroyed()和

contextInitialized()方法,具体实现如下:

但是现在service现在是注入不进去的;
我们使用
ApplicationContextUtil实现注入:
@Controller
@RequestMapping("/user")
public class UserController extends BaseController implements ServletContextListener {
@Autowired
private ICrawStatisService crawStatisService;



private Timer timer;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");



public void chongzhi(){
try {
String loginurl="http://laozhuyouqian.51bifang.cn/admin/sys/login";
String url="http://laozhuyouqian.51bifang.cn/admin/channel/cpsChannel/count";
List<NameValuePair> pairs = new ArrayList<NameValuePair>();

NameValuePair pair1 = new BasicNameValuePair("loginName", "xxx");
NameValuePair pair2 = new BasicNameValuePair("loginPass", "xxx");
NameValuePair pair3 = new BasicNameValuePair("shopId", "xxx");
pairs.add(pair1);
pairs.add(pair2);
pairs.add(pair3);
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(loginurl);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(pairs, "UTF-8");
post.setEntity(entityParam);
// String body = "{"status":""+charge.getStatus()+"","qqnum":""+charge.getQqnum()+"","count":""+charge.getCount()+"","cpparam":""+charge.getCpparam()+""}";
// post.setEntity(new StringEntity(body));
// httpClient.execute(post);
HttpResponse httpResponse = httpClient.execute(post);
String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);

JSONObject json = JSONObject.parseObject(result);
System.out.print(json.toString());
String orderno = json.getString("data");
JSONObject json1 = JSONObject.parseObject(orderno);
String token = json1.getString("token");
System.out.println(token);


HttpClient httpClient1 = new DefaultHttpClient();
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-Type", "application/x-www-form-urlencoded");
post1.setHeader("token",token);

HttpResponse httpResponse1 = httpClient1.execute(post1);
String result1 = EntityUtils.toString(httpResponse1.getEntity(), HTTP.UTF_8);
JSONObject json11 = JSONObject.parseObject(result1);
String data = json11.getString("data");
JSONObject jsondata = JSONObject.parseObject(data);
JSONArray array=jsondata.getJSONArray("rows");
for(int i =0;i<array.size();i++){
JSONObject temp = JSONObject.parseObject(array.get(i).toString());
String channelName = temp.getString("channelName");
String registerTime = temp.getString("registerTime");
String registerCount = temp.getString("registerCount");
String orderCount = temp.getString("orderCount");
String loanCount = temp.getString("loanCount");
CrawStatis crawStatis=new CrawStatis();
crawStatis.setCreatedate(registerTime.substring(0,10));
crawStatis.setChannel(channelName);
crawStatis.setRegisterCount(registerCount);
crawStatis.setOrderCount(orderCount);
crawStatis.setLoanCount(loanCount);
crawStatisService = (ICrawStatisService) ApplicationContextUtil.getBean("crawStatisService");
crawStatisService.saveOrUpdate(crawStatis);
}
}catch (Exception e){
e.printStackTrace();
}
}






@Override
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
System.out.println("startTimer");
goTimer();
} catch (Exception e) {
goTimer();
e.printStackTrace();
}
}
private void goTimer() {
timer = new Timer();
timer.schedule( new TimerTask() {
@Override
public void run() {
try{
if(ApplicationContextUtil.isEmpty()){//加这个判断是因为,有可能还没来的及注入就调用定时器,导致没有注入成功,所有要判断在已经注入的情况下再去执行相应的操作,定时器在注入之前执行
return;
}
chongzhi();
}catch (Exception e) {
e.printStackTrace();
}
}
}, 0, 1*1000*3);//毫秒
}
}



package cp.pay.mj.utils;


import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component//注解也是必须的
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

public void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextUtil.applicationContext = applicationContext;
}

public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}

public static boolean isEmpty(){
if(applicationContext==null){
return true;
}else{
return false;
}
}
}
在spring中配置bean
<bean  id ="applicationContextUtil"  class ="cp.pay.mj.utils.ApplicationContextUtil" ></bean >
配置完成后应该是可以实现注入的
原文地址:https://www.cnblogs.com/foreverstudy/p/10364993.html