首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Spring XML 配置:DOCTYPE DTD 與 xmlns Schema 衝突完整解決方案

     編輯:程式設計綜合問答

錯誤現象


Multiple annotations found at this line:
- The content of element type "beans" must match "(description?,(import|alias|bean)*)".
- Attribute "xsi:schemaLocation" must be declared for element type "beans".
- Attribute "xmlns:xsi" must be declared for element type "beans".
...

根因:混用 DTD 與 Schema 兩種驗證模式

  • DTD 模式:`` — **舊版 (Spring 1.x/2.x)**,不支援 `xmlns:*` 屬性
  • Schema 模式:`` — **現代標準 (Spring 2.0+)**,支援命名空間、AOP、TX、Context 等擴充

**同時宣告兩者會導致 XML 解析器困惑**,產生上述屬性未宣告、內容模型不匹配錯誤。

解決方案:完全移除 DOCTYPE,純 Schema 模式




    
    
    
        
            
            
        
    
    
    

關鍵修正點對照

錯誤寫法正確寫法說明
保留 ``**刪除整行**DTD 不支援 `xmlns:*`,必須捨棄
`spring-beans-2.5.xsd` 版號硬編碼`spring-beans.xsd` **無版號**Spring 會自動解析為當前 Jar 版本對應 XSD
缺少 `xmlns="https://www.springframework.org/schema/beans"`**必須加在 `` 根元素**預設命名空間,讓 `` 等標籤無前綴可用
缺少 `xmlns:context`依需求加入支援 `` 等

Spring 版本對應 XSD 自動解析機制

  • Spring Jar 內 `META-INF/spring.schemas` 映射:`https://www.springframework.org/schema/beans/spring-beans.xsd` → `org/springframework/beans/factory/xml/spring-beans-5.3.xsd`
  • **無版號 XSD 永遠指向當前 classpath 版本**,避免升級 Spring 時需手動改 XML

完整命名空間速查表 (常用)


xmlns:context="https://www.springframework.org/schema/context"      
xmlns:aop="https://www.springframework.org/schema/aop"              
xmlns:tx="https://www.springframework.org/schema/tx"                
xmlns:mvc="https://www.springframework.org/schema/mvc"              
xmlns:jpa="https://www.springframework.org/schema/data/jpa"         
xmlns:security="https://www.springframework.org/schema/security"    

現代替代:Java Config 完全取代 XML


@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
@EnableTransactionManagement
@EnableJpaRepositories("com.example.repository")
public class AppConfig {
    @Bean
    public DataSource dataSource() { ... }
    
    @Bean
    public PlatformTransactionManager txManager(DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }
}

總結

Spring XML 配置錯誤根因:**DTD 與 Schema 衝突**。解決:**刪除 ``、使用無版號 XSD、補全 `xmlns` 命名空間**。現代專案**強烈建議遷移至 Java Config (`@Configuration`)**,享受類型安全、IDE 重構、編譯期檢查優勢。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved