首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring AOP 配置錯誤:Eclipse 無法識別 tx:advice 標籤解決方案

     編輯:Java 相關知識

Spring XML 配置中使用 <tx:advice>、<aop:config> 時,Eclipse 報錯 The prefix "tx" for element "tx:advice" is not bound,原因是缺少命名空間與 Schema 宣告。

錯誤配置


<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
           https://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <tx:advice id="txAdvice">...</tx:advice>  <!-- 報錯:tx 未宣告 -->
</beans>

正確配置模板


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

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="serviceMethods" 
            expression="execution(* com.example.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
    </aop:config>

</beans>

關鍵宣告解析

切點運算式通配符詳解


execution(* com.example.service.*.*(..))
屬性值說明
xmlns:txhttps://www.springframework.org/schema/tx事務命名空間
xmlns:aophttps://www.springframework.org/schema/aopAOP 命名空間
schemaLocation...spring-tx.xsd, spring-aop.xsd對應 XSD 驗證
位置符號含義
1*任意返回型別
2com.example.service固定包路徑
3*包下任意類
4*類中任意方法名
5(..)任意參數列表 (0~N 個)

版本無關寫法 (Spring 3.0+)

移除 XSD 版本號,自動解析當前 Spring 版本對應 Schema:


https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/tx/spring-tx.xsd
https://www.springframework.org/schema/aop/spring-aop.xsd

Java Config 替代方案 (Spring 3.1+)


@Configuration
@EnableTransactionManagement
@EnableAspectJAutoProxy
public class AppConfig {
    @Bean
    public PlatformTransactionManager txManager(DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }
    // @Transactional 註解替代 XML 配置
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved