Java Listener中Spring接口注入的使用


在項目中使用Spring通常使用他的依賴注入可以很好的處理,接口與實現類之間的耦合性,但是通常的應用場景中都是Service層和DAO層,或者web層的話, 也是與Strust2來整合,那么如何在Listener中使用Spring自動注入的接口呢。 接下來開始記錄下今天做的一個小工具。

這個小工具是通過這個Listener來開啟一個線程, 然后定時訪問數據庫中的數據,將數據獲取出來后,然后逐條分析數據里邊的手機號碼,來通過淘寶提供的一個接口來分析手機號的歸屬地。那么在Listener中如何來訪問數據庫呢。下面直接貼代碼:

...

import java.util.ArrayList;
import java.util.List;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.org.rapid_framework.page.Page;


/**
 * Listener的方式在后台執行一線程
 * 
 * @author 
 * 
 */
public class MyListener implements ServletContextListener {
    private MyThread myThread;
    private Logger logger = Logger.getLogger(MyListener.class);

    public void contextDestroyed(ServletContextEvent e) {
        if (myThread != null && myThread.isInterrupted()) {
            myThread.interrupt();
        }
    }

    public void contextInitialized(ServletContextEvent e) {
        String str = null;
        if (str == null && myThread == null) {
            myThread = new MyThread(e);
            myThread.start(); // servlet 上下文初始化時啟動 socket
        }
    }
}

/**
 * 自定義一個 Class 線程類繼承自線程類,重寫 run() 方法,用於從后台獲取並處理數據
 * 
 * @author Champion.Wong
 * 
 */
class MyThread extends Thread {
    private Logger logger = Logger.getLogger(MyThread.class);
    ServletContextEvent _e;
    public MyThread(ServletContextEvent e) {
        _e = e;
    }

    public void run() {
        while (!this.isInterrupted()) {// 線程未中斷執行循環
            IGoldenPhoneManager phoneManager;
            List<GoldenPhone> phoneList = new ArrayList<GoldenPhone>();
            WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(_e.getServletContext());
            phoneManager = (IGoldenPhoneManager) context.getBean("igoldenPhoneManager");
            System.out.println("開始獲取所有電話記錄...");
            int pageSize = 100;
            for (int i = 0; i < 46800; i++) {
                GoldenPhoneQuery query = new GoldenPhoneQuery();
                query.setPageNumber(i);
                query.setPageSize(pageSize);
                Page result = phoneManager.findPage(query);
                if (result != null) {
                    phoneList = result.getResult();
                    System.out.println("獲取所有電話記錄數目:" + result.getResult().size());
                    if (!CollectionUtils.isEmpty(phoneList)) {
                        for (GoldenPhone phoneModel : phoneList) {
                            if (StringUtils.isBlank(phoneModel.getProvinces())) {
                                String provinces = new PhoneService().getPhoneArea(phoneModel.getTel());
                                phoneModel.setProvinces(provinces);
                                phoneManager.update(phoneModel);
                                try {
                                    Thread.sleep(3000);
                                    System.out.println("休息3m鍾...");
                                } catch (InterruptedException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

可以看到,方法中通過

WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(_e.getServletContext()); phoneManager = (IGoldenPhoneManager) context.getBean("igoldenPhoneManager"); 

來獲取一個bean,這樣就能獲取到一個已經注入好的bean了。這里需要注意的是:在web.xml中添加這個偵聽的時候, 需要先引入Spring的Listener然后引入這個自定義的Listener,需要注意前后順序。接下來就是通過開啟一個線程,來處理當前的一些數據邏輯。這段代碼中另外一個注意的地方就是有時,我們在想如何將一個參數傳遞到一個線程中, 上文我的做法是通過構造函數傳入。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM