1)实例化方式一:
dao.StudentDAO是dao中的一个接口,我们创建一个MapperFactoryBean实例,然后注入这俩个接口和sqlSessionFactory(mybatis中提供的SqlSessionFactory接口,MapperFactoryBean会使用SqlSessionFactory创建SqlSession)这两个属性。之后想使用这个接口的话,直接通过spring注入这个bean,然后就可以直接使用了,spring内部会创建一个这个接口的动态代理。
在spring-mybatis.xml配置文件中,加入以下配置:
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds"/>
<!-- 指定映射文件的位置 -->
<property name="mapperLocations" value="classpath:entity/StudentMapper.xml"/>
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="dao.StudentDAO"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
这种方式通常用于工程中的demo测试,比如说junit测试。eg:
public void init() {
String config="spring-mybatis.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
StudentDAO dao=(StudentDAO) ac.getBean("userMapper",StudentDAO.class);
System.out.println("dao+++++++"+dao);
}
2)实例化方式二:(常用方式)
当发现要使用多个MapperFactoryBean的时候,一个一个定义肯定非常麻烦,于是mybatis-spring提供了MapperScannerConfigurer这个类,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。
<!-- 配置MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
指定映射器所在的包名
<property name="basePackage" value="dao"/>
</bean>
以上这段配置会扫描org.mybatis.spring.sample.mapper下的所有接口,然后创建各自接口的动态代理类。测试:
public void init() {
String config="spring-mybatis.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(config);
StudentDAO dao=(StudentDAO) ac.getBean("studentDAO",StudentDAO.class);
}
3)实例化方式三:
有的人喜欢自己写一个注解类@MyBatisRepository(目前鉴于我个人能力有限,暂时不是很了解这个注解类的必要性,在此仅写出个人的理解,如有偏差之处还请各位老大指正。)
package annotations;
public @interface MyBatisRepository {
}
然后在配置文件中这样写:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
指定映射器所在的包名
<property name="basePackage" value="dao"/>
指定注解类(只扫描带有该注解的接口)
<property name="annotationClass" value="annotations.MyBatisRepository"/>
</bean>
同时在mapper接口上加上如下注解:
package dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import annotations.MyBatisRepository;
import entity.Student;
@Repository("studentDao")
@MyBatisRepository
public interface StudentDAO {
public List<Student> findAll();
}
这样spring扫描的时候就会只扫描带有这个注解的接口(StudentDAO.class)。测试的话和上边的方法一样。