1. 程式人生 > >使用MapperScannerConfigurer簡化MyBatis配置

使用MapperScannerConfigurer簡化MyBatis配置

dmi type xmla session tex sse one pac user

MyBatis的一大亮點就是可以不用DAO的實現類。如果沒有實現類,Spring如何為Service註入DAO的實例呢?MyBatis-Spring提供了一個MapperFactoryBean,可以將數據映射接口轉為Spring Bean。

<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
  <property name="mapperInterface" value="dao.UserMapper"/>  
  <property name="sqlSessionFactory
" ref="sqlSessionFactory"/> </bean> </beans>

如果數據映射接口很多的話,需要在Spring的配置文件中對數據映射接口做配置,相應的配置項會很多了。為了簡化配置,在MyBatis-Spring中提供了一個轉換器MapperScannerConfig它可以將接口轉換為Spring容器中的Bean,在Service中@Autowired的方法直接註入接口實例。在Spring的配置文件中可以采用以下所示的配置將接口轉化為Bean。

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer
"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="basePackage" value="dao"/> </bean> <context:component-scan base-package="service"/>

MapperScannerConfigurer將掃描basePackage所指定的包下的所有接口類(包括子類),如果它們在SQL映射文件中定義過,則將它們動態定義為一個Spring Bean,這樣,我們在Service中就可以直接註入映射接口的bean,service中的代碼如下

package service.impl;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  
  
import dao.UserMapper;  
import pojo.User;  
import service.UserService;  
@Service("userService")  
public class UserServiceImpl implements UserService {  
    @Autowired  
    private UserMapper userMapper;  
  
    @Override  
    public User getUser(User user) {  
        return userMapper.getUser(user);  
    }  
}

接下來,創建測試類進行測試

    package test;  
      
    import junit.framework.Assert;  
      
    import org.junit.Test;  
    import org.springframework.context.ApplicationContext;  
    import org.springframework.context.support.ClassPathXmlApplicationContext;  
      
    import pojo.User;  
    import service.UserService;  
      
    public class TestService {  
        @Test  
        public void test(){  
            ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");  
            UserService userService=(UserService)context.getBean("userService");  
            User user=new User();  
            user.setUsername("admin");  
            user.setPassword("admin");  
            User u=userService.getUser(user);  
            Assert.assertNotNull(u);  
        }  
    }  


使用MapperScannerConfigurer簡化MyBatis配置