使用MapperScannerConfigurer简化MyBatis配置

转至:http://blog.csdn.net/u011318776/article/details/52819241

MyBatis的一大亮点就是可以不用DAO的实现类。如果没有实现类,Spring如何为Service注入DAO的实例呢?MyBatis-Spring提供了一个MapperFactoryBean,可以将数据映射接口转为Spring Bean。

 

[java] view plain copy
 
  1. <div><bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
  2.   <property name="mapperInterface" value="dao.UserMapper"/>  
  3.   <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
  4.  </bean>  
  5. </beans>  
  6. </div>  

如果数据映射接口很多的话,需要在Spring的配置文件中对数据映射接口做配置,相应的配置项会很多了。为了简化配置,在MyBatis- Spring中提供了一个转换器MapperScannerConfig它可以将接口转换为Spring容器中的Bean,在Service中 @Autowired的方法直接注入接口实例。在Spring的配置文件中可以采用以下所示的配置将接口转化为Bean。

[java] view plain copy
 
  1.  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  2.   <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
  3.   <property name="basePackage" value="dao"/>  
  4.  </bean>  
  5.  <context:component-scan base-package="service"/>  

MapperScannerConfigurer将扫描basePackage所指定的包下的所有接口类(包括子类),如果它们在SQL映射文件中 定义过,则将它们动态定义为一个Spring Bean,这样,我们在Service中就可以直接注入映射接口的bean,service中的代码如下

 

[java] view plain copy
 
  1. package service.impl;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import dao.UserMapper;  
  7. import pojo.User;  
  8. import service.UserService;  
  9. @Service("userService")  
  10. public class UserServiceImpl implements UserService {  
  11.     @Autowired  
  12.     private UserMapper userMapper;  
  13.   
  14.     @Override  
  15.     public User getUser(User user) {  
  16.         return userMapper.getUser(user);  
  17.     }  
  18. }  

接下来,创建测试类进行测试

 

[java] view plain copy
 
    1. package test;  
    2.   
    3. import junit.framework.Assert;  
    4.   
    5. import org.junit.Test;  
    6. import org.springframework.context.ApplicationContext;  
    7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
    8.   
    9. import pojo.User;  
    10. import service.UserService;  
    11.   
    12. public class TestService {  
    13.     @Test  
    14.     public void test(){  
    15.         ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");  
    16.         UserService userService=(UserService)context.getBean("userService");  
    17.         User user=new User();  
    18.         user.setUsername("admin");  
    19.         user.setPassword("admin");  
    20.         User u=userService.getUser(user);  
    21.         Assert.assertNotNull(u);  
    22.     }  
    23. }  
posted @ 2018-02-02 15:05  杨柳春色  阅读(162)  评论(0编辑  收藏  举报