解決Spring的定時器如何獲取項目的部署路徑

来源:互联网 发布:ikev2搭建 ubuntu 编辑:程序博客网 时间:2024/06/16 05:11

        最近在寫項目的時候遇到在Spring的定時器下需要用到項目路徑的,但是在定時器中,沒法獲取request或者session不能直接調用他的方法直接獲得,那麼怎麼解決這樣的問題呢?其實還是有辦法的,正所謂條條道路通羅馬,spring這麼強大怎麼可能被這點小事給整過去.

         我舉個例子吧,加入我們需要些這麼個定時器,他的需求如下:每天進行一次項目生成的一次性的文件進行刪除

那麼定時器代碼如下:

package com.smartsoft.quartz;import java.io.File;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import com.smartsoft.common.Constant;import com.smartsoft.service.UserService;@Componentpublic class AnnotationQuartz {@AutowiredUserService UserService;@Scheduled(cron = "0 0 0/1 * * ?")public void test() {int days = 2;// TODO定時刪文件SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");Date date = new Date();Calendar calendar = new GregorianCalendar();calendar.setTime(date);for (int i = 1; i <= 30; i++) {calendar.add(calendar.DATE, -1);date = calendar.getTime();String dateStr = sf.format(date);String docx_Report = Constant.get_REALPATH() +"templetUpload\\" + dateStr+"\\docx_Report";String html_Report= Constant.get_REALPATH() +"templetUpload\\" + dateStr+"\\html_Report";String pdf_Report= Constant.get_REALPATH() +"templetUpload\\" + dateStr+"\\pdf_Report";String xlsx_Report= Constant.get_REALPATH() +"templetUpload\\" + dateStr+"\\xlsx_Report";delFolder(docx_Report);delFolder(html_Report);delFolder(pdf_Report);delFolder(xlsx_Report);}}// 删除文件夹// param folderPath 文件夹完整绝对路径public static void delFolder(String folderPath) {try {delAllFile(folderPath); // 删除完里面所有内容String filePath = folderPath;filePath = filePath.toString();java.io.File myFilePath = new java.io.File(filePath);myFilePath.delete(); // 删除空文件夹} catch (Exception e) {e.printStackTrace();}}// 删除指定文件夹下所有文件// param path 文件夹完整绝对路径public static boolean delAllFile(String path) {boolean flag = false;File file = new File(path);if (!file.exists()) {return flag;}if (!file.isDirectory()) {return flag;}String[] tempList = file.list();File temp = null;for (int i = 0; i < tempList.length; i++) {if (path.endsWith(File.separator)) {temp = new File(path + tempList[i]);} else {temp = new File(path + File.separator + tempList[i]);}if (temp.isFile()) {temp.delete();}if (temp.isDirectory()) {delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件delFolder(path + "/" + tempList[i]);// 再删除空文件夹flag = true;}}return flag;}public static void main(String[] args) {System.out.println(AnnotationQuartz.class.getResource("/"));}}

以上代碼很簡單,就是純粹的刪除文件和文件夾,既然是刪除文件,那文件在項目的路徑就必須知道,這項目路徑如何來?看一下代碼

首先,新建一个类如下:

public class InitialServlet extends HttpServlet{private static final long serialVersionUID = 1L;     @Override    public void init() throws ServletException {        super.init();        System.out.println("开始intitServlet");        String realPath = getServletContext().getRealPath("/");        Constant.set_REALPATH(realPath);    }}

用语获取项目路径并把它保存在Constant的常量里

public class Constant {public final static int PAGE_SIZE_10 = 10; //初始化分页         // 项目路径,可以使用单例进行存放    public static String _REALPATH = "";         public static String get_REALPATH() {        return _REALPATH;    }    public static void set_REALPATH(String _REALPATH) {        Constant._REALPATH = _REALPATH;    }}

特殊一点,给他提供下get,set

重点是让InitialServlet在项目已启动就保存项目的路径所提,在web.xml定义这么一段初始化

<servlet><servlet-name>InitialServlet</servlet-name><servlet-class>com.smartsoft.util.InitialServlet</servlet-class><load-on-startup>0</load-on-startup></servlet>

这样一来,无论项目何时启动,在何时我们都能通过Constant.get_REALPATH()获取项目路径了,这里利用到的只是servlet的一些小知识而已,不懂的请先了解servlet吧



1 0
原创粉丝点击