码迷,mamicode.com
首页 > 其他好文 > 详细

自动加载的两种办法

时间:2016-05-03 10:45:44      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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()");
}

}

 

自动加载的两种办法

标签:

原文地址:http://www.cnblogs.com/lanliying/p/5453951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!