public class SampleRealm extends AuthorizingRealm{
@Autowired
private LoginService loginService;
......
}
现象在自定义AuthorizingRealm子类SampleRealm中Service类无法注入成功
抛出该异常 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type,首先我回去检测LoginService子类是否做了如下Service层定义
@Service("loginService")
public class LoginServiceImpl implements LoginService {},检查已经定了说明代码编写的没问题;
然后查找配置文件是否有问题,首先要了解web.xml的启动原理,可以查看该文章http://blog.csdn.net/ahou2468/article/details/69948990(SpringMVC启动过程详解(li)),会发现首先会读取Spring监听器配置类ContextLoaderListener,它读取web.xml中配置的context-param中的配置文件,提前在web容器初始化前准备业务对应的Application context;将创建好的Application context放置于ServletContext中,为springMVC部分的初始化做好准备:
context-param参数配置如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
application.xml文件中的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 引入jdbc配置文件 start -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<!--要是有多个配置文件,只需在这里继续添加即可 -->
</list>
</property>
</bean>
<!-- 引入jdbc配置文件 end -->
<!-- 引入配置文件 start -->
<import resource="classpath:activiti-context.xml"/>
<import resource="classpath:spring-mybatis.xml"/>
<import resource="classpath:spring-shiro-stand-alone.xml"/>
<!-- 引入配置文件 end -->
</beans>
这样我们就会发现在读取spring-mvc.xml配置文件之前已经读取结合spring框架其他框架(mybatis,shiro)的配置,因此需要在启动Shiro配置读取前配置自动扫描Service层的类,我选在在spring-mybatis.xml文件中配置自动扫描Service层的类,如下:
<context:component-scan base-package="com.mimhope.pms.*.service"/>
这要就可以保证在SampleRealm类中注入的LoginService对象可以自动注入成功;
在读取完context-param参数配置中的配置以后才会进行DispatchServlet初始化进而读取Spring-mvc.xml文件中的配置,包括controller包的自动扫描操作;
假如是AuthorizingRealm类中调用Service,可能需要注意的地方就是在Service层调用Dao层时使用@Resource添加Dao类对象的注入:
@Service("loginService")
public class LoginServiceImpl implements LoginService {
@Resource
private SysUserMapper sysUserMapper;
}
如有分析有问题的地方还请对指正,谢谢。