專案中 Shiro Realm 實作類使用 @Autowired 注入 Service 失效 (為 null)。經排查,根因是 **Spring 父子容器掃描順序衝突**:DispatcherServlet 容器在事務配置前掃描 Service,導致事務失效,同時 Realm 實例化時機早於 Service 注入完成。
ApplicationContextUtils.getApplicationContext().getBean() 手動查找。static 靜態欄位注入 (惡心但有效)。專案採用經典 ContextLoaderListener (根容器) + DispatcherServlet (子容器) 架構:
component-scan) 集中在子容器,根容器僅載入 shiro.xml,導致:
tx:annotation-driven) 在掃描**之後**載入,Service 失去事務增強。applicationContext.xml (或 root-context.xml)<context:component-scan base-package="com.example" /> <!-- 掃描 Service、DAO、Realm 等 -->
<import resource="mybatis.xml" /> <!-- 資料源、SqlSessionFactory、事務管理器 -->
<import resource="redis-context.xml" />
<import resource="spring-shiro-web.xml" /> <-- Shiro 配置,含 Realm Bean 定義 -->
spring-mvc.xml (DispatcherServlet)<context:component-scan base-package="com.example">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
<!-- 僅掃描 Controller、Interceptor 等 Web 組件 -->