The mechanism of MyBatis automatic scanning mapper from Mapperscannerconfigurer view

Source: Internet
Author: User

First, we look at the inheritance and realization of mapperscannerconfigurer.

Here we focus on the Beandefinitionregistrypostprocessor interface: it inherits the Beanfactorypostprocessor, Used to register some additional beandefinition in the container before the beanfactorypostprocessor is initialized.

You're supposed to have a little idea here, right? Yes, it just scans the class that we gave to the basepackage, and then generates the beandefinition and adds it to the container.

Let's start with the source code, we'll look at the method called when the Beandefinitionregistrypostprocessor is initialized:

public void Postprocessbeandefinitionregistry (Beandefinitionregistry registry) throws Beansexception {if (this.proces    Spropertyplaceholders) {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)); }

Here we first look at Classpathmapperscanner this class, can be seen from the name (Scanner), it is to go to scan core class. And in addition to the last line, the rest of the code is configured with this scanner.

Here according to the name we can guess, the last line Scanner.scan (...) is to scan the mapper and add it to the beandefinition. In order to verify our ideas, follow the inside to see:

public int Scan (String ... basepackages) {int beancountatscanstart = This.registry.getBeanDefinitionCount ();d Oscan ( basepackages)//Register annotation config processors, if Necessary.if (this.includeannotationconfig) { Annotationconfigutils.registerannotationconfigprocessors (this.registry);} Return This.registry.getBeanDefinitionCount ()-Beancountatscanstart;}

It is not the Classpathmapperscanner class that is found, but the Classpathbeandefinitionscanner class, And Classpathbeandefinitionscanner under Spring's package. So go back and look at the definition of Classpathbeandefinitionscanner:

public class Classpathmapperscanner extends Classpathbeandefinitionscanner

Well, it does inherit the Org.springframework.context.annotation.ClassPathBeanDefinitionScanner, and we can see that it covers several ways:


Doscan (...), cooked? If you are not familiar, please see the scan method. The logic of monitoring is in fact doscan (...) , let's focus on this override method:

  @Override public set<beandefinitionholder> doscan (String ... basepackages) {set<beandefinitionholder> be    Andefinitions = Super.doscan (basepackages); if (Beandefinitions.isempty ()) {Logger.warn ("No MyBatis Mapper is found in '" + arrays.tostring (basepackages) + "' Package. Please check your configuration. "); else {for (Beandefinitionholder holder:beandefinitions) {genericbeandefinition definition = (genericbeande        finition) holder.getbeandefinition ();               if (logger.isdebugenabled ()) {Logger.debug ("Creating Mapperfactorybean with Name '" + holder.getbeanname ()        + "' and '" + definition.getbeanclassname () + "' Mapperinterface"); }//The Mapper interface is the original class of the beans//But, the actual class of the beans is Mapperfa        Ctorybean definition.getpropertyvalues (). Add ("Mapperinterface", Definition.getbeanclassname ());     Definition.setbeanclass (Mapperfactorybean.class);   Definition.getpropertyvalues (). Add ("Addtoconfig", this.addtoconfig);        Boolean explicitfactoryused = false; if (Stringutils.hastext (This.sqlsessionfactorybeanname)) {definition.getpropertyvalues (). Add ("SqlSessionFactory"          , New Runtimebeanreference (This.sqlsessionfactorybeanname));        Explicitfactoryused = true; } else if (this.sqlsessionfactory! = null) {definition.getpropertyvalues (). Add ("Sqlsessionfactory", this.sqlsess          Ionfactory);        Explicitfactoryused = true; } if (Stringutils.hastext (this.sqlsessiontemplatebeanname)) {if (explicitfactoryused) {Logger . Warn ("Cannot use Both:sqlsessiontemplate and sqlsessionfactory together.          Sqlsessionfactory is ignored. "); Definition.getpropertyvalues (). Add ("Sqlsessiontemplate", New Runtimebeanreference (          This.sqlsessiontemplatebeanname));        Explicitfactoryused = true; } else if (this.sqlsessiontemplate! = null) {if (Explicitfactoryused) {Logger.warn ("Cannot use Both:sqlsessiontemplate and sqlsessionfactory together.          Sqlsessionfactory is ignored. ");          Definition.getpropertyvalues (). Add ("Sqlsessiontemplate", this.sqlsessiontemplate);        Explicitfactoryused = true;  } if (!explicitfactoryused) {if (logger.isdebugenabled ()) {Logger.debug ("Enabling Autowire by          Type for Mapperfactorybean with Name ' "+ holder.getbeanname () +" '. ");        Definition.setautowiremode (Abstractbeandefinition.autowire_by_type);  }}} return beandefinitions; }

The first step is to see that the Doscan (...) of the parent class is called. method, the parent class of the Doscan (..) This is not released here, it is the core of spring automatic scanning mechanism, that is, we register:

<context:component-scan base-package= "Com.test"/>

This thing will be used, it can help us to automatically register @controller, @Service and other components.

In essence, it is also by scanning these classes and adding them to the beandefinition, so the Doscan (...) above through the parent class. The method actually encapsulates the class under the base-package we set as beandefinition and adds it to a set set. That's Doscan (..). The first sentence gets the beandefinitions.

But slightly different from the parent class, after getting all the beandefinition, it's not really going to be injected into the class in the container, remember how the MyBatis was configured when you injected mapper into spring manually:

<bean id= "Usermapper" class= "Org.mybatis.spring.mapper.MapperFactoryBean" >  <property name= " Mapperinterface "value=" Org.mybatis.spring.sample.mapper.UserMapper "/>  <property name=" Sqlsessionfactory "ref=" Sqlsessionfactory "/></bean>

The beandefinition of the mapper registered above by automatic scanning is similar to this:

<bean id= "Usermapper" class= "Com.test.a.mapper.usermapper" ></bean>

The key is this class, so you need to convert and inject attributes into it, both mapperinterface and sqlsessionfactory are necessary.

This completes the Mapper automatic scan, do not know this to say whether the thought clear ~





The mechanism of MyBatis automatic scanning mapper from Mapperscannerconfigurer view

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.