Eliminating DAO Implementation Classes with MyBatis-Spring MapperScannerConfigurer

MyBatis-Spring provides a powerful feature that eliminates the need for manual DAO implementation classes. Instead of creating concrete implementations, the framework can automatically convert mapper intefraces into Spring beans through MapperFactoryBean.

When working with individual mapper interfaces, the traditional approach requires explicit bean configuration:

<bean id="orderDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="mappers.OrderMapper"/>
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

This configuration becomes unwieldy when dealing with numerous mapper interfaces. The MapperScannerConfigurer class solves this problem by automatically scanning and registering mapper interfaces as Spring beans.

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

The scanner examines all interfaces within the specified base package. Any interface that has a corresponding SQL mapping definition gets automatically registered as a Spring bean, enabling direct dependency injection into service classes.

Service layer implementation example:

package services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import mappers.OrderMapper;
import domain.Order;
import services.OrderService;

@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Order findOrder(Order order) {
        return orderMapper.findOrder(order);
    }
}

Unit test verification:

package tests;

import junit.framework.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import domain.Order;
import services.OrderService;

public class OrderServiceTest {
    @Test
    public void testFindOrder() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        OrderService orderService = (OrderService) ctx.getBean("orderService");
        Order criteria = new Order();
        criteria.setOrderId("ORD-001");
        criteria.setStatus("pending");
        Order result = orderService.findOrder(criteria);
        Assert.assertNotNull(result);
    }
}

Tags: MyBatis Spring MapperScannerConfigurer DAO Dependency Injection

Posted on Wed, 19 Aug 2026 16:06:33 +0000 by stilgar