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>
在本文中,我们遇到了一个在Spring MVC应用中使用`WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext())`返回 null 的问题。这个问题发生在`contextInitialized()`方法中,当尝试从Servlet上下文中获取`WebApplicationContext`并进一步获取`DataSource`时。为了解决这个问题,文章可能涉及了在`web.xml`配置文件中正确设置监听器和上下文配置的步骤。
471

被折叠的 条评论
为什么被折叠?



