SoFunction
Updated on 2025-03-08

Detailed explanation of the sqlSessionFactory injection method of MapperScannerConfigurer

Explanation of the SQLSessionFactory injection method of MapperScannerConfigurer

First of all, there is a configuration in Mybatis that is very convenient, which saves us time to write DaoImpl (Dao layer implementation class), which is package scanning. . . .

Let's first look at a piece of code:

  <!-- 4:Configure ScanDaoInterface package,Dynamic implementationDaointerface,Inject toSpringIn the container -->
  <bean class="">
    <!--Here is the point to talk about today-->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    <!-- Give the scanned oneDaointerface包 -->
    <property name="basePackage" value=""></property>
  </bean>

In MapperScannerConfigurer, we know that there are four ways to inject sqlSessionFactory, namely sqlSessionFactoryBeanName, sqlSessionTemplate, sqlSessionTemplateBeanName, and sqlSessionFactory are outdated, so we are using sqlSessionFactoryBeanName. Next, let’s talk about the benefits of this and why we need to use it!

Reason 1:

Inject sqlSessionFactory (can be configured without configuration) Only when multiple data sources are configured, there will be multiple sqlSessionFactory. You can specify which sqlSessionFactory by changing the properties (comprehensive online summary)

Reason 2 (key point):

Inject sqlSessionFactory, the value afterward is the name of the bean of the SqlSessionFactory, that is, the id of the sqlSessionFactory. When our mapperscannerconfigurer is started, our file may not be loaded. In this way, the DataSource it gets is wrong, because properties like ${} have not been replaced yet. Therefore, through the BeanName post-processing method, when we use our Mybatis, it will find our corresponding sqlSessionFactory, in order to prevent it from initializing our sqlSessionFactory in advance.

Thank you for reading, I hope it can help you. Thank you for your support for this site!