由於 MyBatis 用 SqlSessionFactory 來建立 SqlSession ,SqlSessionFactoryBuilder 建立 SqlSessionFactory ,而在 Mybatis-Spring 中提供了繼承自 Spring 接口 FactoryBean 的 SqlSessionFactoryBean 類,它提供 getObject() 方法來獲取 SqlSessionFactory 。因此能夠用基於Java配置的方式配置 SqlSessionFactory 。sql
MybatisDataConfig配置類配置了MyBatis的dataSource、sql語句xml配置文件路徑、數據庫類型包路徑數據庫
1 @Configuration 2 public class MybatisDataConfig { 3 4 private DataSource dataSource; 5 6 @Autowired 7 public MybatisDataConfig(DataSource dataSource) { 8 this.dataSource = dataSource; 9 } 10 11 /** 12 * 必須指定名稱 sqlSessionFactory. 13 */ 14 @Bean("sqlSessionFactory") 15 public SqlSessionFactory getBean() throws Exception { 16 SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); 17 factoryBean.setDataSource(dataSource); 18 19 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 20 factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml")); 21 factoryBean.setTypeAliasesPackage("com.test.entity"); 22 return factoryBean.getObject(); 23 } 24 25 }
爲了減小xml配置,Mybatis-Spring還提供了 MapperScannerConfigurer 類,它能夠掃描映射類,自動建立 MapperFactoryBean 來吧dao注入給service,也就是說service能夠直接經過@Autowired等方式,直接注入dao層接口實例,而dao層的接口不須要其餘額外的配置。app
1 /** 2 * <p>MybatisScannerConfig 和 MybatisDataConfig 須要分開寫.</p> 3 * <p>而 MybatisScannerConfig 比 MybatisDataConfig 加載早.</p> 4 * <p>因此要定義@AutoConfigureAfter.</p> 5 * <p>不然 MybatisDataConfig 先加載會找不到 dataSource.</p> 6 * @see MybatisDataConfig 7 */ 8 @Configuration 9 @AutoConfigureAfter(MybatisDataConfig.class) 10 public class MybatisScannerConfig { 11 12 /** 13 * 基於Java配置sqlSessionFactory,掃描dao層. 14 * @return 配置實例 15 */ 16 @Bean 17 public MapperScannerConfigurer getConfig() { 18 MapperScannerConfigurer configurer = new MapperScannerConfigurer(); 19 configurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); 20 configurer.setBasePackage("com.test.dao"); 21 return configurer; 22 } 23 }
項目Demo:MiniJavaWebui