如何将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
- 如何将Spring的配置文件放到web.xml中
- 如何将下面xml放到datagridview中
- Spring框架中如何读取Spring的XML配置文件
- Spring Boot 将配置文件放到jar外部
- spring的配置文件在web.xml中加载的方式
- web.xml中引入SPRING配置文件classpath的含义
- 一个spring web的配置文件web.xml
- web.xml中如何设置配置文件的加载路径
- web.xml 记载spring 配置文件的写法
- 如何将金山词霸的音标放到Word中
- web.xml中定义的Spring的XML配置文件启动顺序
- web.xml中定义的Spring的XML配置文件启动顺序
- 将url放到配置文件
- Spring Boot教程 - 3. 将配置文件放到jar外部
- web.xml中spring如何通过ContextLoaderListener初始化的
- SpringMVC中web.xml的常用配置文件
- web.xml配置文件中ContextLoaderListener的作用
- Struts + spring web.xml加载spring的配置文件
- 如何在DOS窗口中显示UTF-8字符
- windows命令schtasks逆向
- Qt5.5.1编译出来的程序出现libgcc_s_dw2-1.dll的解决方案
- python实现windows ie代理切换
- Gradlle 全解析(Android官方技术文档翻译)
- 如何将Spring的配置文件放到web.xml中
- C#总结
- 带有可变参数的方法
- java开发环境配置(1)——JDK配置
- linux makefile教程
- [笔记向] Tricks
- 指针和数组的转换
- AbstractMap 源代码
- 【CS学习】——机房收费系统用例图介绍