Mybatis mapperscannerconfigurer Auto-scan injects mapper interface generation agent into spring

Source: Internet
Author: User

Mybatis mapperscannerconfigurer Auto-scan injects mapper interface generation agent into spring

MyBatis can configure Mapperfactorybean to generate proxies for mapper interfaces when integrated with spring. For example

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

  The proxy class created by Mapperfactorybean implements the Usermapper interface and injects it into the application. Because the agent is created in the runtime environment (runtime, translator note), the specified mapper must be an interface, not a specific implementation class.

 The above configuration has a big disadvantage, that is, the system has a lot of configuration files need to be written manually, so the above methods are rarely used.

  It is not necessary to register all the mappers in the Spring XML configuration file. Instead, you can use a mapperscannerconfigurer , which will look for mappers under the classpath and automatically build them into Mapperfactorybean.

To create a mapperscannerconfigurer, you can add the following code to the Spring configuration:

class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" >  <property name= "Basepackage" value = "Org.mybatis.spring.sample.mapper"/></bean>

The Basepackage property lets you set the basic package path for the Mapper interface file . You can use a semicolon or comma as a delimiter to set more than one package path. Each mapper will be recursively searched in the specified package path.

  Note: There is no need to specify Sqlsessionfactory or Sqlsessiontemplate, because Mapperscannerconfigurer will create Mapperfactorybean and then assemble automatically.

  However, if you use more than one DataSource, automatic assembly may fail. In this case, you can use the Sqlsessionfactorybeanname or Sqlsessiontemplatebeanname property to set the correct bean name. This is how it is configured, note that the bean name is required, not the bean's reference, and therefore the Value property replaces the usual ref:

<property name= "Sqlsessionfactorybeanname" value= "Sqlsessionfactory"/>

 Mapperscannerconfigurer supports filtering by creating a mapper from the specified creation interface or annotations . The Annotationclass property specifies the name of the note to look for. The Markerinterface property specifies the parent interface to look for. If both are specified, the mapper added to the interface will match the two criteria. By default, both properties are null, so all interfaces given in the base package can be loaded as mappers.

The discovered mapper will use spring to name the auto-detect component (refer to the Spring Manual's 3.14.4) default naming policy. that is, if no annotations are found, it uses the non-uppercase, non-fully qualified class name of the mapper. However, if a @named annotation of @component or JSR-330 is found, it gets the name. Note that you can configure to Org.springframework.stereotype.Component, javax.inject.Named (if you use JSE 6) or your own annotations (which are definitely self-explanatory), which The sample annotations will be used as generators and name providers.

Next, let's look at the source code of the Mapperscannerconfigurer class to see how it is automatically scanned.

 Public voidPostprocessbeandefinitionregistry (Beandefinitionregistry Registry)throwsbeansexception {if( This. Processpropertyplaceholders)    {processpropertyplaceholders (); } Classpathmapperscanner Scanner=NewClasspathmapperscanner (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)); }

Convert the Mapper interface into a Mapperfactorybean code in the 17 line this method, let's track it and look at it.

@Override PublicSet<beandefinitionholder>Doscan (String ... basepackages) {Set<BeanDefinitionHolder> beandefinitions =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=(genericbeandefinition) 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 Bean//but, the actual class of the beans is Mapperfactorybean//set the type of the interface inDefinition.getpropertyvalues (). Add ("Mapperinterface", Definition.getbeanclassname ()); //set the True type of the bean MapperfactorybeanDefinition.setbeanclass (Mapperfactorybean.class); //do you want to add the Mapper interface to the MyBatis config ?Definition.getpropertyvalues (). Add ("Addtoconfig", This. Addtoconfig); Booleanexplicitfactoryused =false; //query in the spring container if the name of the sqlsessionfactorybeanname is not empty//for multiple data sources        if(Stringutils.hastext ( This. Sqlsessionfactorybeanname)) {definition.getpropertyvalues (). Add ("Sqlsessionfactory",NewRuntimebeanreference ( This. Sqlsessionfactorybeanname)); Explicitfactoryused=true; } Else if( This. sqlsessionfactory! =NULL) {definition.getpropertyvalues (). Add ("Sqlsessionfactory", This. sqlsessionfactory); Explicitfactoryused=true; }        //query in the spring container if the name of the sqlsessiontemplatebeanname is not empty//for multiple data sources        if(Stringutils.haif(Stringutils.hastext ( This. Sqlsessiontemplatebeanname)) {          if(explicitfactoryused) {Logger.warn ("Cannot use Both:sqlsessiontemplate and sqlsessionfactory together. Sqlsessionfactory is ignored. "); } definition.getpropertyvalues (). Add ("Sqlsessiontemplate",NewRuntimebeanreference ( 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); }      }    }    //When this collection returns, the spring container registers all of the contents in the container.    returnbeandefinitions; }

(go) Mybatis mapperscannerconfigurer Auto-scan injects mapper interface generation agent into spring

Related Article

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.