You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署spring-mongo.xml时找不到mongo:mongo声明,无法创建MongoTemplate Bean

解决Spring-Mongo XML配置中“Not able to found declaration for mongo:mongo”错误

嘿,这个报错我之前帮不少开发者排查过,核心原因要么是XML里的Schema声明不全,要么是依赖没配对,咱们一步步来搞定:

1. 补全xsi:schemaLocation的MongoDB Schema地址

看你贴的配置,schemaLocation部分明显截断了——XML解析器找不到mongo:mongo标签的定义,就是因为没给它完整的Schema地址。把这部分补全成下面这样:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/data/mongo
           http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

重点是最后两行的Spring Data MongoDB Schema,必须完整写对,这是让解析器识别mongo命名空间下标签的关键。

2. 确认依赖包是否到位

如果是Maven项目,检查pom.xml里有没有引入Spring Data MongoDB的核心依赖,版本要和你的Spring主版本兼容:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>2.2.6.RELEASE</version> <!-- 替换成和你Spring版本匹配的号 -->
</dependency>

要是手动导包的话,得确保spring-data-mongodb-x.x.x.RELEASE.jar、spring-data-commons.jar还有MongoDB的驱动包都已经放进项目的类路径里,缺一个都可能出问题。

3. 检查Mongo标签的配置写法

确认你的mongo:mongo标签和后续的MongoTemplate配置是正确的,比如:

<!-- 注册Mongo实例 -->
<mongo:mongo host="localhost" port="27017"/>
<!-- 创建DB工厂 -->
<mongo:db-factory dbname="your-database-name" mongo-ref="mongo"/>
<!-- 实例化MongoTemplate -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory"/>
</bean>

这里mongo:mongo会自动生成id为mongo的Bean,供db工厂引用,进而创建MongoTemplate。

额外小提示

如果你的Spring版本比较新(比如Spring 3.x及以上),建议换成mongo:client标签,因为旧的mongo:mongo已经被标记为过时了,用法类似:

<mongo:client host="localhost" port="27017" id="mongoClient"/>
<mongo:db-factory dbname="your-database-name" mongo-client-ref="mongoClient"/>

内容的提问来源于stack exchange,提问作者A.G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:07:11