Spring XML配置文件头部需包含XML声明和beans根元素,正确声明命名空间及xsi:schemaLocation中的XSD地址(推荐HTTPS),支持按需扩展context、aop、tx等命名空间,且XSD地址无需版本号。

Spring框架XML配置文件的头部信息主要包含XML声明和根元素的命名空间(namespace)及对应schema位置(xsi:schemaLocation)。关键是要正确声明Spring的XSD约束,确保配置文件能被Spring容器识别和校验。
基础XML声明与beans根元素
每份Spring XML配置文件都应以标准XML声明开头,接着是根标签,并指定Spring官方提供的XSD地址。最简可用写法如下:
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
常用命名空间扩展(按需添加)
如果用到AOP、事务、上下文等模块,需补充对应命名空间和schemaLocation。例如同时使用注解驱动、AOP和事务管理:
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
- 每个
xmlns:xxx声明一个命名空间前缀(如context),后续可用context:component-scan等标签 -
xsi:schemaLocation中,每对URI必须严格一一对应:先写命名空间URI,再写其XSD网络地址(空格分隔) - 推荐使用
https://开头的地址(Spring 4.3+ 官方已切换为HTTPS),避免HTTP重定向或证书问题
注意版本兼容性
Spring 5.3+ 已停止维护DTD方式,且不再支持spring-beans-3.0.dtd等旧式声明。XSD地址无需写具体版本号(如spring-beans-5.3.xsd),统一用无版本的spring-beans.xsd即可 —— Spring会自动匹配当前jar包中的对应版本。
如果你用的是较老的Spring 3.x或4.x,仍可继续用http://协议地址,但建议升级到HTTPS以保证稳定性。
基本上就这些。只要命名空间声明完整、schemaLocation配对正确,IDE(如IntelliJ或Eclipse)就能正常提示和校验,Spring容器也能顺利加载配置。










