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>
| 屬性 | 值 | 說明 |
|---|---|---|
| xmlns:tx | https://www.springframework.org/schema/tx | 事務命名空間 |
| xmlns:aop | https://www.springframework.org/schema/aop | AOP 命名空間 |
| schemaLocation | ...spring-tx.xsd, spring-aop.xsd | 對應 XSD 驗證 |
| 位置 | 符號 | 含義 |
|---|---|---|
| 1 | * | 任意返回型別 |
| 2 | com.example.service | 固定包路徑 |
| 3 | * | 包下任意類 |
| 4 | * | 類中任意方法名 |
| 5 | (..) | 任意參數列表 (0~N 個) |
移除 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
@Configuration
@EnableTransactionManagement
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public PlatformTransactionManager txManager(DataSource ds) {
return new DataSourceTransactionManager(ds);
}
// @Transactional 註解替代 XML 配置
}