使用MapperScannerConfigurer简化MyBatis配置



使用MapperScannerConfigurer简化MyBatis配置

https://blog.csdn.net/u011318776/article/details/52819241

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

  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。

  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中的代码如下

  1. package service.impl;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import dao.UserMapper;
  5. import pojo.User;
  6. import service.UserService;
  7. @Service( "userService")
  8. public class UserServiceImpl implements UserService {
  9. @Autowired
  10. private UserMapper userMapper;
  11. @Override
  12. public User getUser(User user) {
  13. return userMapper.getUser(user);
  14. }
  15. }
接下来,创建测试类进行测试

  1. package test;
  2. import junit.framework.Assert;
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. import pojo.User;
  7. import service.UserService;
  8. public class TestService {
  9. @Test
  10. public void test(){
  11. ApplicationContext context= new ClassPathXmlApplicationContext( "applicationContext.xml");
  12. UserService userService=(UserService)context.getBean( "userService");
  13. User user= new User();
  14. user.setUsername( "admin");
  15. user.setPassword( "admin");
  16. User u=userService.getUser(user);
  17. Assert.assertNotNull(u);
  18. }
  19. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值