在spring使用过程中,通常的做法是让服务器启动时即实例化所有的bean,这样做在一定程度上提高了web应用的速度。加载完成后,在用的时候便可以通过
ApplicationContext ctx = WebApplicationContextUtils.getWebApplictionContext();
Test test = (Test)ctx.getBean("test");
得到想要的bean--test了。
要配置在服务器启动加载applicationcontext通常有两种方法:
(1)ContextLoaderListener
具体配置是在web.xml中增加:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
(2)ContextLoaderServlet
具体配置是在web.xml中增加:
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
无论通过上面的哪一种配置都可以达到服务器启动即实例化bean的目的。
如果要想指定applicationContext.xml的位置可以在增加:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appContext.xml</param-value>
</context-param>
通过以上配置就可以达到在服务器启动时实例化指定的applicationContext.xml配置文件了。