不启动服务加载spring配置文件进行测试

本文介绍了一种不依赖Web服务器的手动加载Spring配置文件的方法,通过FileSystemXmlApplicationContext类实例化ApplicationContext对象,并展示了如何通过过滤指定前缀的配置文件来加载特定的Spring Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不启动web服务器加载spring 配置文件 并调用spring bean
我们手动加载spring的配置文件
这里我们使用 ApplicationContext ctx = new FileSystemXmlApplicationContext(paths, true);
这个构造函数来进行ApplicationContext的初始化
其中第一个参数是一个String[]数组 里边的每个对象是spring配置文件的绝对路径
当你的spring的根目录为WebContent/WEB-INF/config/spring 举例如下:
File springPath = new File("WebContent/WEB-INF/config/spring");
File[] files = springPath.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (!name.startsWith("spring-default")&&!name.startsWith("spring-remote"))
return true;
else
return false;
}
});
String[] paths = new String[files.length];
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
String abPath = files[i].getAbsolutePath();
paths[i] = abPath;
}
}
ApplicationContext ctx = new FileSystemXmlApplicationContext(paths, true);

然后就可以用ctx.getBean("")方法来取得spring bean对象了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值