ssm和shiro整合,shiro的自定义的realm不能自动注入的问题

在自定义realm的时候注入的时候就会报错,去掉注解@Autowired 运行就会没有问题。错误的原因应该在于注解无法注入
 
     
  1. @Autowired
  2. private UserService userService;
  3. // 设置realm的名称
  4. @Override
  5. public void setName(String name) {
  6. super.setName("customRealm");
  7. }
这是eclipse报的异常情况。
 
  
  1. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in
  2. class path resource [spring-shiro/spring-shiro.xml]:
  3. Cannot resolve reference to bean 'securityManager' 
  4. while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: 
  5. Error creating bean with name 'securityManager' defined in class path resource [spring-shiro/spring-shiro.xml]:
  6. Cannot resolve reference to bean 'myRealm' while setting bean property 'realm'; 
  7. nested exception is org.springframework.beans.factory.BeanCreationException: 
  8. Error creating bean with name 'myRealm':
  9. Injection of autowired dependencies failed; 
  10. nested exception is org.springframework.beans.factory.BeanCreationException: 
  11. Could not autowire field: private com.englishload.service.UserService com.englishload.realm.MyRealm.userService; 
  12. nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
  13. [com.englishload.service.UserService]
  14. found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 
  15. Dependency annotations: 
  16. {@org.springframework.beans.factory.annotation.Autowired(required=true)}
解决方案: 
因为shiro的realm属于Filter,简单说就是初始化realm时, spring 还未加载相关业务Bean,那么解决办法就是将springmvc的配置文件加载提前。
这是改变后的代码,将SpringMVC的配置文件在 <context-param>中加载。
 
   
  1. <!-- spring mybatis配置 和shiro-->
  2. <context-param>
  3. <param-name>contextConfigLocation</param-name>
  4. <param-value>classpath:spring-mybatis/spring-mybatis.xml,
  5. classpath:spring-shiro/spring-shiro.xml,
  6. classpath:/springmvc-servlet/springmvc-servlet.xml
  7. </param-value>
  8. </context-param>
  9. <!-- springmvc的配置 -->
  10. <servlet>
  11. <servlet-name>springmvc</servlet-name>
  12. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  13. <init-param>
  14. <param-name>contextConfigLocation</param-name>
  15. <param-value>classpath:/springmvc-servlet/springmvc-servlet.xml</param-value>
  16. </init-param>
  17. <load-on-startup>1</load-on-startup>
  18. </servlet>
  19. <servlet-mapping>
  20. <servlet-name>springmvc</servlet-name>
  21. <url-pattern>/</url-pattern>
  22. </servlet-mapping>
  23. <!-- shiro的filter -->
  24. <!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->

猜你喜欢

转载自blog.csdn.net/architect_csdn/article/details/80253126