2 u011699931 u011699931 于 2016.04.28 12:31 提问

springmvc定时任务注入问题
数据库中有一个字段会不断更新,并且本地有一个文件存储着这个字段的信息,我写了一个定时器,自动更新文件,但是出问题了,下面是定时器代码:
 package org.ramer.diary.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.ramer.diary.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

/**
 * schedule job:
 *  execute  every ten seconds;
 *  query tags from table topic and remove duplicates ,and compare to local file "/xml/tags.xml";
 *  new tags will be append to file.
 *
 * @author ramer
 *
 */
@Controller
public class ScheduleWork implements ServletContextListener {

  /**
   * get millis for 'time'
   * @param time "HH:mm:ss"
   * @return
   */
  private long getTimeMillis(String time) {
    try {
      DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
      DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
      Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
      return curDate.getTime();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return 0;
  }

  @Override
  public void contextDestroyed(ServletContextEvent arg0) {

  }

  @Autowired
  TopicService topicService;
  @Value("#{diaryProperties['tags.xml.position']}")
  private String file;

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    // execute every ten seconds
    long oneDay = 10 * 1000;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
    // start now
    long initDelay = getTimeMillis(simpleDateFormat.format(new Date()))
        - System.currentTimeMillis();
    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
    // start execute job
    executor.scheduleAtFixedRate(() -> {
      System.out.println("----------start update tags-----------");
      // tags in database
      System.out.println(topicService);
      System.out.println(file);
      List<String> tags = topicService.getAllTags();
      // remove duplicate
      StringBuilder stringBuilder = new StringBuilder();
      for (String string : tags) {
        stringBuilder.append(string + ";");
      }
      String[] strings = stringBuilder.toString().split(";");
      // Arrays.asList will return a proxy with doesn't implement add() and remove(),so create a list.
      List<String> tagslist = Arrays.asList(strings);
      tagslist = new ArrayList<>(tagslist);
      for (int i = 0; i < tagslist.size(); i++) {
        for (int j = i + 1; j < tagslist.size(); j++) {
          if (tagslist.get(i).equals(tagslist.get(j))) {
            tagslist.remove(j);
            j--;
          }
        }
      }
      // tags no duplicate.
      tags = tagslist;
      System.out.println("tags in database: ");
      for (String string : tags) {
        System.out.println("\t" + string);
      }
      List<String> tagsInFile = new ArrayList<>();
      try {
        // read tags in local file
        tagsInFile = FileUtils.readTag(file, servletContextEvent.getServletContext());
      } catch (Exception e) {
        System.out.println("Exception ScheduleWork(Line 111)");
        e.printStackTrace();
      }
      System.out.println("文件中的tags: ");
      for (String string : tagsInFile) {
        System.out.println("\t" + string);
      }
      // less than tags in database ,so each the tags in local file
      for (int i = 0; i < tags.size(); i++) {
        if (!tagsInFile.contains(tags.get(i))) {
          tagsInFile.add(tags.get(i));
          i++;
        }
      }
      System.out.println("update tags: ");
      for (String string : tagsInFile) {
        System.out.println("\t" + string);
      }

      try {
        // update tags in local file
        FileUtils.writeTag(tagsInFile, file, servletContextEvent.getServletContext());
      } catch (Exception e) {
        System.out.println("Exception ScheduleWork(Line 129)");
        e.printStackTrace();
      }

    }, initDelay, oneDay, TimeUnit.MILLISECONDS);
  }

}

运行时,发现上面的‘topicService’和file总是null,也就是注入失败了,请问是什么原因呢?

1个回答

zjysource
zjysource   2016.04.28 14:48

请把springmvc的容器配置文件和工程的web.xml文件拿出来看看哈。光看你这个文件,是找不到原因滴。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!