package com;
import java.sql.PreparedStatement;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SystemListener implements ServletContextListener {
private final static Logger logger = Logger.getLogger(SystemListener.class);
public void contextDestroyed(ServletContextEvent arg0) {
//System.out.println("this is contextDestroyed() !!!");
logger.info("this is contextDestroyed() !!!");
}
public void contextInitialized(ServletContextEvent arg0) {
//System.out.println("this is contextInitialized() !!!");
logger.info("this is contextInitialized() !!!");
try {
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
DataSource dataSource2 = (DataSource) ctx.getBean("dataSource");
/*
DataSourceUtil.setDataSource(dataSource2);
//ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-database.xml");
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext-database.xml"});
DataSource dataSource2 = (DataSource) ac.getBean("dataSource");
*/
logger.info("*******:"+dataSource2.getConnection().toString());
} catch (Exception e) {
logger.error(e);
}
}
}
以上代码中红色部分得到null ,在web.xml中加入以下代码:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>