Spring扫描Mybatis的mapper接口的三种配置方式

  • mybatis支持与spring结合使用,使得mybatis中的mapper接口可以作为spring容器中的bean被应用代码中相关类,如Service类,通过@Autowired自动注入进来。在使用方面需要在项目中引入以下包:

    org.mybatis
    mybatis-spring
    1.3.1


  • 在spring中可以通过三种方式来自动扫描获取应用代码的mybatis相关的mapper接口定义:
  1. 在applicationContext.xml中使用

   
   ...
   
    
   
   		
   		
   		
   
   
   
   
   ...
   


2.在applicationContext.xml中使用bean标签注册MapperScannerConfigurer,即


   
   ...
   
    
   
   		
   		
   		
   
   
   
   		
   
   
   ...
   


  1. 如果应用是使用Java配置方式而不是XML,则在@Configuration配置类使用@MapperScan或者@MapperScans注解:
@Configuration
@MapperScan("org.xyz.jblog.dao")
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        return new PooledDataSource("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test", "root", "root");
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBeansessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        return sessionFactory.getObject();
    }
}

你可能感兴趣的:(mybatis)