博客
关于我
spring application.xml在项目中的几种解析方式
阅读量:709 次
发布时间:2019-03-17

本文共 1629 字,大约阅读时间需要 5 分钟。

在Java项目中,Spring的applicationContext.xml文件有多种解析方式。下面从不同角度解析这些方法,并结合常见场景提供实用技巧。

一、基于类路径的applicationContext.xml解析

最常见的方式是通过ClassPathXmlApplicationContext来加载applicationContext.xml。

ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");Object bean = cxt.getBean("beanId");

这种方法适用于标准开发环境中的普通应用。

二、基于文件系统的applicationContext.xml解析

当项目部署路径明确时,可以使用FileSystemXmlApplicationContext。

ApplicationContext cxt = new FileSystemXmlApplicationContext("C:/path/to/applicationContext.xml");Object bean = cxt.getBean("beanId");

这种方式适合需要严格控制配置文件路径的情况。

三、基于资源的低级解析方式

通过Resource和XmlBeanFactory来实现基本的xml解析。

Resource res = new ClasspathResource("applicationContext.xml");XmlBeanFactory factory = new XmlBeanFactory(res);Object bean = factory.getBean("beanId");

这种方式适合对Spring容器进行操作时的底层实现。

四、jsp 页面中的applicationContext.xml解析

在Struts等框架中,通过自定义Bean类来灵活调用Spring-managed bean。

public class GetBean {    private XmlBeanFactory factory;    public GetBean() {        Resource res = new ServletContextResource(            ServletActionContext.getServletContext(), "/WEB-INF/transaction.xml");        factory = new XmlBeanFactory(res);    }    public Object getBean(String beanName) {        XmlWebApplicationContext ctx = new XmlWebApplicationContext();        ServletContext servletContext = ServletActionContext.getServletContext();        ctx.setServletContext(servletContext);        ctx.setConfigLocations(new String[] { "/WEB-INF/transaction.xml" });        ctx.refresh();        return ctx.getBean(beanName);    }}

这种方式适合前端直接调用后台Spring bean的场景。

在实际开发中,可以根据项目需求灵活选择适合的方式。例如,在本地开发环境中使用第一种方法,在特定部署环境中使用第二种方法,或者在web应用中结合第四种方法实现特定功能。

转载地址:http://wjcez.baihongyu.com/

你可能感兴趣的文章
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
MQTT工作笔记0009---订阅主题和订阅确认
查看>>
ms sql server 2008 sp2更新异常
查看>>
MS UC 2013-0-Prepare Tool
查看>>
msbuild发布web应用程序
查看>>
MSB与LSB
查看>>
MSCRM调用外部JS文件
查看>>
MSCRM调用外部JS文件
查看>>
MSEdgeDriver (Chromium) 不适用于版本 >= 79.0.313 (Canary)
查看>>