1. 程式人生 > >shiro錯誤 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

shiro錯誤 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

最近在弄個小模組,用的是spring mvc + mybites + spring shiro


在弄shiro 的Realm自動注入的時候總是報錯,

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sam.project.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:618)
... 44 more


糾結許久,終於在網上查詢到了解決方案

Shiro的Realm 是屬於Filte,因此在web.xml裡面載入的時候會先載入Filete,然後才載入到Spring,所以Realm中@Autowired總是找不到bean,其實容器啟動後,web.xml的配置載入順序是

ServletContext--context-param--listener--filter--servlet 

因此,只要把Spring配置檔案提前載入即可,即:在web.xml中把spring配置檔案放在Shiro配置檔案之前,如下圖:



按照上面的配置修改後,重啟服務即可!

其他的注入配置不變,不需要設定什麼@Resource,還是用之前的@Autowired。