shiro框架,自定義realm注入service失敗解決辦法

最近在學習使用shiro框架,按照網上的方法照葫蘆畫瓢去配置,結果出現了問題.

其中最爲嚴重的就是 自定義的realm在引用service時,自動注入失敗.

報錯如下:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in ServletContext resource [/WEB-INF/config/spring-shrio.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in ServletContext resource [/WEB-INF/config/spring-shrio.xml]: Cannot resolve reference to bean 'databaseRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'databaseRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blog.service.ILoginService com.blog.realm.DatabaseRealm.loginSerivce; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blog.service.ILoginService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
這一大堆英文看着都懵,總而言之,言而總之一句話,自動注入失敗

問題分析: 查閱網絡上大量的問題分析,得到結論shiro 自定義realm的認證階段屬於filter,當時的spring bean還沒有讀取進來。

解決方案就是: 在執行讀取shiro配置文件中的filter之前,要先去把註冊的bean執行了.

那誰會去註冊bean呢. 就是spring-mvc的xml中的

<!-- 自動掃描的包名 ,使Spring支持自動檢測組件,如註解的Controller-->
    <context:component-scan base-package="com.blog.controller" />
    <context:component-scan base-package="com.blog.service"/>
	<context:component-scan base-package="com.blog.realm"/>

因此 

你可以在執行shiro的xml之前先執行一遍spring-mvc的xml,這樣就可以先註冊bean了.但是有個問題,之後你還是要再一次執行spring-mvc.xml,執行了兩次,會不會出現問題呢,不好說啊

也可以這樣做

在shiro的xml中 把這個語句加上,也就是說註冊掃描service包在shiro的xml執行,

這樣一來,realm中的service就可以注入成功了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章