您的位置:首页 > 其它

IOC容器在web容器中初始化——(一)两种配置方式

2017-12-28 14:59 323 查看
参考文章https://www.geek-share.com/detail/2636541864.htmlhttps://www.geek-share.com/detail/2681918800.html。   最近在研究IOC容器在web容器中初始化的过程。阅读了源码,参照了很多文章,在这里记录一下。   使用的web容器为tomcat7.spring的jar包为4.3.7.RELEASE版本。   我们可以通过web.xml配置文件web容器中声明spring容器。有以下两种方式: 1:通过配置监听器来实现
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2:通过配置servlet来实现 由于web容器再启动时优先先扫描<listener>与<context-param>两个标签,所以推荐通过配置监听器的方式实现。 下面是通过配置监听器实现ioc容器在web容器中注册的方式。 Spring提供了ServletContextListener接口,以及他的实现类ContextLoaderListener。 它实现了创建初始化ServletContext后的事件监听和销毁ServletContext前的事件监听。 下面是web.xml中的代码
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>ffback</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/ApplicationContext1.xml,
classpath:spring/ApplicationContext2.xml
</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<context-param>标签用与配置ServletContext的参数。 我们配置了webAppRootKey和contextConfigLocation两个参数。 webAppRootKey:web项目的绝对路径。同一个web容器中,不同的项目要有不同的webAppRootKey。 contextConfigLocation:指定要初始化的文件的位置。默认
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: