錯誤堆疊
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'shiroFilter' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(...)
常見原因與修復
- Bean 名稱不匹配:
spring-shiro.xml 中定義 <bean id="shiroFilter" ...>,但 web.xml 的 DelegatingFilterProxy filter-name 必須與 Bean ID **完全一致**(區分大小寫)。
- 配置文件未加載:
web.xml 的 contextConfigLocation 需包含 spring-shiro.xml:<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml, classpath:spring-shiro.xml</param-value>
</context-param>
- 命名空間衝突:若有多個 Spring 容器(ContextLoaderListener + DispatcherServlet),確保
shiroFilter 定義在**父容器**(ContextLoaderListener 加載的配置)中,否則 Filter 找不到 Bean。
- Bean 延遲初始化:若
shiroFilter 依賴 securityManager 等 Bean,檢查依賴關係是否循環,必要時加 lazy-init="true" 或調整聲明順序。
驗證步驟
- 啟動專案,觀察控制台是否輸出
Pre-instantiating singletons 含 shiroFilter。
- 在 Controller 注入
@Autowired ShiroFilterFactoryBean shiroFilter 測試是否可用。
- 若仍失效,啟用 Spring DEBUG 日誌:
logging.level.org.springframework=DEBUG。
配置範例(正確)
<!-- spring-shiro.xml -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
<property name="filterChainDefinitions">
<value>
/login* = anon
/** = authc
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>
<bean id="myRealm" class="com.shiro.service.MonitorRealm"/>