• 自动加载的两种办法


    1、spring

    配置init-method方法

    例子如下

    spring-xml------------------------------------------------

    <context:annotation-config/>  

    <bean id="dataProcessor" class="com.thread.DataProcessor" scope="singleton"  init-method="start"  destroy-method="cleanUp"/> 

    java---------------------------------------------

    package com.thread;

    import java.util.HashMap;
    import java.util.Map;

    public class DataProcessor {
    private static DataProcessor dataProcessor=null;
    private DataProcessor(){}

    public static DataProcessor getInstance(){
    if(dataProcessor==null){
    dataProcessor=new DataProcessor();
    }
    return dataProcessor;
    }

    /**数据转存线程数*/
    private static int DATA_HANDLER_NUM = 4;
    /**线程状态存储*/
    public static Map<String, Boolean> threadStatusMap = new HashMap<String, Boolean>();

    public void start(){
    String name;
    for(int i = 0 ; i < DATA_HANDLER_NUM; i++){
    name = "dataHandlerRunnerThread " + i;
    threadStatusMap.put(name, true);
    new Thread(new DataHandlerRunner(threadStatusMap), name).start();
    }
    }

    public void cleanUp(){
    System.out.println("cleanUp");
    }

    }

    2、servlet

    web.xml   ------------------------------------------

    <listener>
    <listener-class>com.listener.MyServletContextListener</listener-class>
    </listener>

    Java 添加监听器------------------------------------

    package com.listener;

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

    import com.thread.DataProcessor;

    /**
    * Application Lifecycle Listener implementation class MyServletContextListener
    *
    */
    public class MyServletContextListener implements ServletContextListener {

    /**
    * Default constructor.
    */
    public MyServletContextListener() {
    System.out.println("MyServletContextListener()");
    }

    /**
    * @see ServletContextListener#contextInitialized(ServletContextEvent)
    */
    public void contextInitialized(ServletContextEvent arg0) {

    DataProcessor d=DataProcessor.getInstance();
    d.start();
    System.out.println(arg0.toString());
    }

    /**
    * @see ServletContextListener#contextDestroyed(ServletContextEvent)
    */
    public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("contextDestroyed()");
    }

    }

  • 相关阅读:
    自己用的C++编码规范
    飘逸的python
    编译Sqoop2错误解决
    怎样设置linux中Tab键的宽度(可永久设置)
    系统分析师零散知识点
    Hadoop权威指南学习笔记一
    Spring获取request、session以及servletContext
    RequestContextHolder获取request和response
    Spring MVC 中RequestContextHolder获取request和response
    缓存清理
  • 原文地址:https://www.cnblogs.com/lanliying/p/5453951.html
Copyright © 2020-2023  润新知