spring - Spring配置文件XML bean配置需要在文件的开头
问题描述
使用以下 Spring 配置,我com.Test2
在使用 DEV 配置文件时加载,并com.Test1
在所有其他情况下加载:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="bean1"
class="com.Test1">
</bean>
<beans profile="DEV">
<bean id="bean1"
class="com.Test2">
</bean>
</beans>
</beans>
将 Spring 配置文件配置移动到文件的开头:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<beans profile="DEV">
<bean id="bean1"
class="com.Test1">
</bean>
</beans>
<bean id="bean1"
class="com.Test2">
</bean>
</beans>
IntelliJ IDE 报告错误:
Invalid content was found starting with element '{"http://www.springframework.org/schema/beans":bean}'. One of '{"http://www.springframework.org/schema/beans":beans}' is expected.
为什么会报告此错误?为什么要求在文件开头设置 Spring 配置文件?
解决方案
报告错误是因为根据XML 模式,在第二种情况下,元素的顺序不正确:
如您所见,任何<bean>
声明都必须在任何嵌套<beans>
的 .
Spring 文档中也指出了此限制:
也可以避免
<beans/>
在同一文件中拆分和嵌套元素,如以下示例所示:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
<!-- other bean definitions -->
<beans profile="development">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
</beans>
已
spring-bean.xsd
被限制为仅允许文件中的最后一个元素。这应该有助于提供灵活性,而不会在 XML 文件中产生混乱。
推荐阅读
- c# - PdfiumViewer Pdfium 异常 - VS2017 创建的项目必须是 .Net 4.0 然后升级到任何更高版本
- php - 如何隐藏多个收件人电子邮件地址 laravel 发送邮件
- node.js - 使用 node.j 和 socket.io 流式传输网络摄像头视频
- angular - AppComponent.html:7 错误类型错误:_co.getPosts 不是 Object.eval 的函数 [as handleEvent]
- haskell - 如何传递一个空白页面?
- javascript - 在angularjs中接收序列化对象作为查询字符串参数
- ios - 多线程违规 剩下的就是荣誉(失败)
- mysql - mysql IF-Statement 的问题:提供更改的值
- android - 安卓通知不显示
- c# - 使用复杂命令渲染 Powershell 输出