zoukankan      html  css  js  c++  java
  • 使用MapperScannerConfigurer简化MyBatis配置

    MyBatis的一大亮点就是可以不用DAO的实现类。

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

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

    如果数据映射接口很多的话,需要在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);
        }
    }
  • 相关阅读:
    mysql 使用SUM()函数查询时,如果没有任何记录的时候 返回的结果为null
    不重复的有序集合,TreeSet的用法
    spring+springMVC+mybatis项目中 多数据源的配置
    程序的位置和功能划分
    团队合作-如何避免JS冲突
    CSS的常见问题
    函数传参的应用--修改文本的值
    应用自定义属性、索引值实现带略缩图的图片轮播
    PC和手机的区别就是各种各样的屏幕,响应式布局来适应屏幕
    CSS3动画@keyframes
  • 原文地址:https://www.cnblogs.com/alsf/p/9295736.html
Copyright © 2011-2022 走看看