<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- SqlSessionFactory对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- <property name="dataSource" ref="dataSource"></property> -->
<property name="typeAliasesPackage" value="com.sxt.pojo"></property>
</bean>
<!-- 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sxt.mapper"></property>
<!-- <property name="sqlSessionFactory" ref="factory"></property> -->
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
全局配置属性为:default-autowire="byName" 自动注入
配置如上,可以正常运行,问题如下:
1. MapperScannerConfigurer不使用:<property name="sqlSessionFactory" ref="factory"></property>的原因在于
a.自动注入的优先级比较高,针对那些有类对象的属性的类,会优先加载
b.MapperScannerConfigurer中有很多对象属性的类,此时初始化sqlSessionFactory时,会寻找factory,而factory中有dataSource属性会自动注入名为dataSource的bean,但此时配置文件尚未加载,所以会报错。
c.而使用<property name="sqlSessionFactoryBeanName" value="factory"></property>相当于占位,因为sqlSessionFactoryBeanName是字符串类型
2. 基于上述解释,我不能理解为啥:SqlSessionFactoryBean中也有类对象的属性:dataSource,dataSource会自动注入id为dataSource的bean,此时配置文件就已经加载了???它为啥不报错可以加载配置文件???