JSP学习笔记(五十):spring中自动加载配置文件,及读取方法

配置web.xml,添加如下内容:

    <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
posted @ 2008-09-16 21:08  魔豆  阅读(2052)  评论(0编辑  收藏  举报