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还没有读取进来。
解决方案:换一种方式进行注入
写一个工具类
@Component
public class ApplicationContextUtils implements ApplicationContextAware {@Autowiredprivate static ApplicationContext context;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.context=applicationContext;}public static Object getBean(String name){return context.getBean(name);}}
需要使用的地方调用方法
@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("-----------------------------");String principal = (String) token.getPrincipal();Object userServiceImpl = ApplicationContextUtils.getBean("userServiceImpl");System.out.println("aaaaaaaaaaaaaaa"+userServiceImpl);if("xiaochen".equals(principal)){return new SimpleAuthenticationInfo(principal,"123",this.getName());}return null;}
}