原文鏈接https://zhhll.com.cn/2021/%E6%A1%86%E6%9E%B6/spring/web%E5%BA%94%E7%94%A8%E4%BD%BF%E7%94%A8spring/
web應(yīng)用使用spring
對于java而言,使用最多的還是web開發(fā),如何在web應(yīng)用中使用spring呢,web應(yīng)用中沒有main方法,而且必須在servlet容器加載時(shí)就創(chuàng)建spring的IOC容器,之前在學(xué)習(xí)Servlet的時(shí)候有講到一個Servlet監(jiān)聽器,可以監(jiān)聽ServletContext、HttpSession、ServletRequest等對象的創(chuàng)建和銷毀
所以可以實(shí)現(xiàn)ServletContextListener接口,重寫contextInitialized方法來實(shí)現(xiàn)spring的IOC容器的創(chuàng)建
public interface ServletContextListener extends EventListener {
void contextInitialized(ServletContextEvent var1);
void contextDestroyed(ServletContextEvent var1);
}
在web.xml中配置listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指明配置文件所在位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
由于本身的博客百度沒有收錄,博客地址https://zhhll.com.cn