<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
这样在web容器启动时,将自动加载spring的配置文件,配置文件有多个时,可以用空格,或者逗号,或者冒号隔开。
下面我们就可以直接使用了,而不用再通过ClassPathXmlApplicationContext等方式重新加载,下面是获取的代码:
ServletContext sc = ServletActionContext.getServletContext(); //获取ServletContext,在不同的情景,获取方式不同,这里是struts2里action类里的获取方式 WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); ac.getBean("beanid"); //这里获得配置文件里对应的bean id
别忘了在jsp中import用到的包