首页 > 解决方案 > 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 配置文件?

标签: 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 文件中产生混乱。


推荐阅读