MapperScannerConfigurer 做用詳解

自動掃描 將Mapper接口生成代理注入到Springjava

<!-- DAO接口所在包名,Spring會自動查找其下的類 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.em" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
  • MapperFactoryBean 建立的代理類實現了 UserMapper 接口,而且注入到應用程序中
  • 把Mapper接口轉換成MapperFactoryBean
    • 其實在SqlSessionFactoryBean 裏面就已經實現了註冊了 MapperProxyFactory 到Mybatis
    • 這裏作的是把它們託管到spring
{
    if (this.processPropertyPlaceHolders) {
      processPropertyPlaceHolders();
    }

    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
    scanner.setAddToConfig(this.addToConfig);
    scanner.setAnnotationClass(this.annotationClass);
    scanner.setMarkerInterface(this.markerInterface);
    scanner.setSqlSessionFactory(this.sqlSessionFactory);
    scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
    scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
    scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
    scanner.setResourceLoader(this.applicationContext);
    scanner.setBeanNameGenerator(this.nameGenerator);
    scanner.registerFilters();
    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }
  • 注意,無論前後順序
    • SqlSessionFactoryBean 繼承了InitializingBean 接口

      • 會在全部spring 註冊完成後,執行afterPropertiesSet方法
      • public void afterPropertiesSet() throws Exception {
            Assert.notNull(this.dataSource, "Property 'dataSource' is required");
            Assert.notNull(this.sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
            this.sqlSessionFactory = this.buildSqlSessionFactory();
        }
相關文章
相關標籤/搜索