如何将Spring的配置文件放到web.xml中

来源:互联网 发布:淘宝蓝冠店赚钱 编辑:程序博客网 时间:2024/06/10 01:18

        经过一段时间的使用,笔者已经可以初步搭建Spring的开发环境了。但是每次调用bean时都需要实例化一个ClassPathXmlApplicationContext对象,并把bean.xml文件作为参数传给它,相当繁琐,而且太死。那有没有办法将配置文件路径统一存放到web.xml里哪?经过一段时间的学习探索,现将方法归纳如下:

        首先在web.xml中增加如下一段配置:

  <listener>    <listener-class>            org.springframework.web.context.ContextLoaderListener        </listener-class>  </listener>

        这句话是增加一个监听器,监听Spring配置文件的变化。当配置文件的内容发生变化后,Spring自动初始化相关的组件。

        然后再在web.xml中增加如下配置:

  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:resources/ApplicationContext.xml</param-value>  </context-param>

        这个配置是告诉Spring从哪里读取配置信息。上面这个配置是告诉Spring去WEB-INF/classes下的resources文件夹下的ApplicationContext.xml中获取配置信息。

        接下来就是代码中写法的变化了。跟之前入门中介绍的每次调用bean时都需要首先new一个ClassPathXmlApplicationContext对象不同,现在只需要在servlet中按如下方式声明即可获取到ApplicationContext对象:

ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); 

        然后通过ac.getBean();方法来获取到配置文件中配置的bean了。

        顺便多说一句,如果Bean对应的类中又调用了第二个组件,就不需要再像第一个组件一样需要声明一个ApplicationContext对象了,只需要将第二个组件的id作为property放到第一个组件的bean节点中就可以了:

       <bean id="config" class="com.sm.threedapd.config.impl.WebXMLConfig"></bean>       <bean id="userdao" class="com.sm.threedapd.authority.data.impl.CUserMongoDBDAO">       <property name="iconfig" ref="config"/>       </bean>       <bean id="userauthority" class="com.sm.threedapd.authority.component.impl.CUserAuthority">       <property name="iuserdao" ref="userdao"/>       </bean>
       上面的配置说明userauthority引用了userdao这个bean,而bean又引用了config这个bean。

       配置好后只需要在调用类的头部定义一个对应的接口名,再加上getter和setter方法即可(以CUserAuthority为例):

private IUserDAO iuserdao = null;public IUserDAO getIuserdao() {return iuserdao;}public void setIuserdao(IUserDAO iuserdao) {this.iuserdao = iuserdao;}



1 0
原创粉丝点击