1: xml配置
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.xxx.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
2: 在扫描的包下使用 @MapperScan(“com.xxx.xxx.dao”) ,不支持占位表达式
@Configuration
@MapperScan("com.xxx.xxx.dao")
public class MybatisConfig {
}
3: 在扫描的包下使用 @Bean注册MapperScannerConfigurer
@Configuration
public class MybatisConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//可使用配置文件引入包名
mapperScannerConfigurer.setBasePackage("com.xxx.xxx.dao");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
Junit测试,locations指定具体的配置文件
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mvc.xml", "classpath:spring-mybatis.xml"})
public class UserServiceTest {
@Resource
private UserDao userDao;
@Test
public void test() throws Exception {
System.out.println(userDao);
}
}