Spring-mybatis结合的底层原理

1.项目前期准备

1.1 导入maven jar包

xml 复制代码
 <dependencies>
    <!-- spring依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!-- spring事务依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!-- mybatis和spring集成依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- mysql驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <!-- 阿里的连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

1.2项目相关的文件夹

说明:

  1. mapper文件夹:存所有的sql语句的接口
  2. service文件夹:存所有具体的实现的方法
  3. spring-mybatis文件夹:存所有整合spring和mybatis的文件
  4. resources文件夹存所有的资源文件

1.2.1 UserMapper.java文件

java 复制代码
package com.nq.mapper;


import org.apache.ibatis.annotations.Select;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 0:24
 */
public interface UserMapper {

    @Select("select 'user'")
    String selectById();
}

1.2.2 AppConfig.java文件

java 复制代码
package com.nq.service;

import org.springframework.context.annotation.ComponentScan;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:59
 */
@ComponentScan("com.nq")
public class AppConfig {
}

1.2.3 UserService.java文件

java 复制代码
package com.nq.service;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:45
 */
@Component
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public void test(){
       System.out.println(userMapper.selectById());
    }

}

1.2.4 mybatis.xml文件

java 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
  <environments default="development">
    <environment id="development">
      <!-- 使用jdbc事务管理 -->
      <transactionManager type="JDBC"/>
      <!-- 数据库连接池 -->
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&amp;useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
</configuration>

1.2.5 Test.java文件

java 复制代码
package com.nq.service;


import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.io.IOException;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/27 23:48
 */
public class Test {
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
        context.register(AppConfig.class);
        context.refresh();

        UserService userService=(UserService)context.getBean("userService");
        userService.test();
    }
}

说明:由于UserMapper是接口类型,不能被spring加载,所以spring加载的时候这里就要解决接口不能够被加载的情况,其二;由于UserMapper是执行sql语句,所有需要Mybatis生成UserMapper代理对象注入到UserMapper类型当中。

2.手写spring-mybatis执行过程

2.1 NickelFactoryBean.java文件

java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 16:00
 */
@Component
public class NickelFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        Object proxyInstance = Proxy.newProxyInstance(NickelFactoryBean.class.getClassLoader(), new Class[]{UserMapper.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });
        return proxyInstance;
    }

    @Override
    public Class<?> getObjectType() {
        return UserMapper.class;
    }
}

说明:这里让UserMapper接口成为一个bean对象,这样程序就不会报错了

说明:这里确实让UserMapper成为一个bean对象了,但是这里会有一个问题,假如我们建立一个OrderMappe文件的话,这里不能识别OrderMapper对象

2.2建立OrderMapper对象和UserService对象

1.OrderMapper.java对象

java 复制代码
package com.nq.mapper;


import org.apache.ibatis.annotations.Select;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 0:24
 */
public interface OrderMapper {

    @Select("select 'order'")
    String selectById();
}

2.UserService.java对象修改

java 复制代码
package com.nq.service;
import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:45
 */
@Component
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;

    public void test(){
       System.out.println(userMapper.selectById());
        System.out.println(orderMapper.selectById());
    }

}

3.测试结果


说明:无法读取到OrderMapper对象

2.3让每一个mapper文件都成为bean对象

1.修改NickelFactoryBean.java文件,这里可以建立一个外部对象的形式,对所有的接口进行赋值

java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 16:00
 */
public class NickelFactoryBean implements FactoryBean {

    private Class mapperInterface;

    public NickelFactoryBean(Class mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @Override
    public Object getObject() throws Exception {
        Object proxyInstance = Proxy.newProxyInstance(NickelFactoryBean.class.getClassLoader(), new Class[]{mapperInterface}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method.getName());
                return null;
            }
        });
        return proxyInstance;
    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }
}

注意:这里需要去掉@Component注解,不然有这个注解spring将会加载一次,这和多个mapper去使用相违背。

2.Test方法中指定对对象成为bean对象

java 复制代码
package com.nq.service;


import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import com.nq.mybatis.spring.NickelFactoryBean;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.io.IOException;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/27 23:48
 */
public class Test {
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
        context.register(AppConfig.class);

        AbstractBeanDefinition beanDefinition= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(NickelFactoryBean.class);
        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);//userMapper  UserMapper代理对象
        context.registerBeanDefinition("userMapper",beanDefinition);

        AbstractBeanDefinition beanDefinition1= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition1.setBeanClass(NickelFactoryBean.class);
        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);//orderMapper  OrderMapper代理对象
        context.registerBeanDefinition("orderMapper",beanDefinition1);


        context.refresh();

        UserService userService=(UserService)context.getBean("userService");
        userService.test();
    }
}

3.Test结果显示


说明;这里我们把每一个mapper接口创建为bean的形式,但是这里有一个问题,假如出现第三mapper文件,我们在这里需要又去添加一个,思考这里有什么方式去注册bean呢

2.4NickelBeanDefinitionRegistryPostProcess.java文件通过继承BeanDefinitionRegistryPostProcessor去注册对应的接口

java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:17
 */
@Component
public class NickelBeanDefinitionRegistryPostProcess implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        AbstractBeanDefinition beanDefinition= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(NickelFactoryBean.class);
        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);//userMapper  UserMapper代理对象
        registry.registerBeanDefinition("userMapper",beanDefinition);

        AbstractBeanDefinition beanDefinition1= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition1.setBeanClass(NickelFactoryBean.class);
        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);//orderMapper  OrderMapper代理对象
        registry.registerBeanDefinition("orderMapper",beanDefinition1);

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}

说明;通过这种获取方式,依然没有解决新加mapper文件的时候,需要增加修改代码的形式,所以这里我们需要通过spring扫描的方式去修改mapper文件的动态获取

2.5我们通过提供注解的形式,得到需要扫描的路径,提供NickelMapperScan注解

java 复制代码
package com.nq.mybatis.spring;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:24
 */
@Retention(RetentionPolicy.RUNTIME)//运行时
@Target(ElementType.TYPE)//注解只能写在类上面
public @interface NickelMapperScan {
    String value();
}

2.6ImportBeanDefinitionRegistrar实现接口的方式我们也能够进行注册

2.6.1修改NickelBeanDefinitionRegistryPostProcess文件

java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:17
 */
//@Component
public class NickelBeanDefinitionRegistryPostProcess implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
//        AbstractBeanDefinition beanDefinition= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//        beanDefinition.setBeanClass(NickelFactoryBean.class);
//        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);//userMapper  UserMapper代理对象
//        registry.registerBeanDefinition("userMapper",beanDefinition);
//
//        AbstractBeanDefinition beanDefinition1= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//        beanDefinition1.setBeanClass(NickelFactoryBean.class);
//        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);//orderMapper  OrderMapper代理对象
//        registry.registerBeanDefinition("orderMapper",beanDefinition1);

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}

2.6.2创建NickelImportBeanDefinitionRegisty.java实现接口ImportBeanDefinitionRegistrar

java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:32
 */
public class NickelImportBeanDefinitionRegisty implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        AbstractBeanDefinition beanDefinition= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(NickelFactoryBean.class);
        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);//userMapper  UserMapper代理对象
        registry.registerBeanDefinition("userMapper",beanDefinition);

        AbstractBeanDefinition beanDefinition1= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition1.setBeanClass(NickelFactoryBean.class);
        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);//orderMapper  OrderMapper代理对象
        registry.registerBeanDefinition("orderMapper",beanDefinition1);
     }
}

2.6.3这里我们需要NickelImportBeanDefinitionRegisty生效,需要在AppConfig中导入

java 复制代码
package com.nq.service;

import com.nq.mybatis.spring.NickelImportBeanDefinitionRegisty;
import com.nq.mybatis.spring.NickelMapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:59
 */
@ComponentScan("com.nq")
@NickelMapperScan("com.nq.mapper")
@Import(NickelImportBeanDefinitionRegisty.class)
public class AppConfig {
}

2.6.4测试运行效果

2.7获取扫描路径

2.7.1把注解移动到扫描类上

1.修改AppConfig文件

java 复制代码
package com.nq.service;

import com.nq.mybatis.spring.NickelImportBeanDefinitionRegisty;
import com.nq.mybatis.spring.NickelMapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:59
 */
@ComponentScan("com.nq")
@NickelMapperScan("com.nq.mapper")
public class AppConfig {
}

2.修改NickelMapperScan文件

java 复制代码
package com.nq.mybatis.spring;

import org.springframework.context.annotation.Import;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:24
 */
@Retention(RetentionPolicy.RUNTIME)//运行时
@Target(ElementType.TYPE)//注解只能写在类上面
@Import(NickelImportBeanDefinitionRegisty.class)
public @interface NickelMapperScan {
    String value();
}

3在NickelImportBeanDefinitionRegisty获取扫描的路径

java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:32
 */
public class NickelImportBeanDefinitionRegisty implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        //获取扫描路径
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(NickelMapperScan.class.getName());
        String path = (String)annotationAttributes.get("value");
        System.out.println(path);

        AbstractBeanDefinition beanDefinition= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(NickelFactoryBean.class);
        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);//userMapper  UserMapper代理对象
        registry.registerBeanDefinition("userMapper",beanDefinition);

        AbstractBeanDefinition beanDefinition1= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition1.setBeanClass(NickelFactoryBean.class);
        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);//orderMapper  OrderMapper代理对象
        registry.registerBeanDefinition("orderMapper",beanDefinition1);
     }
}


说明:打印结果如下

4.通过spring的扫描逻辑获取扫描路径

1.创建类NickelClassPathBeanDefinitionScan继承spring扫描类ClassPathBeanDefinitionScanner
java 复制代码
package com.nq.mybatis.spring;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/29 14:31
 */
public class NickelClassPathBeanDefinitionScan extends ClassPathBeanDefinitionScanner {

    public NickelClassPathBeanDefinitionScan(BeanDefinitionRegistry registry) {
        super(registry);
    }
}
2.NickelImportBeanDefinitionRegisty获取NickelClassPathBeanDefinitionScan得到扫描类
java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:32
 */
public class NickelImportBeanDefinitionRegisty implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        //获取扫描路径
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(NickelMapperScan.class.getName());
        String path = (String)annotationAttributes.get("value");
        System.out.println(path);

        NickelClassPathBeanDefinitionScan nickelClassPathBeanDefinitionScan=new NickelClassPathBeanDefinitionScan(registry);
        nickelClassPathBeanDefinitionScan.scan(path);

        AbstractBeanDefinition beanDefinition= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(NickelFactoryBean.class);
        beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);//userMapper  UserMapper代理对象
        registry.registerBeanDefinition("userMapper",beanDefinition);

        AbstractBeanDefinition beanDefinition1= BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition1.setBeanClass(NickelFactoryBean.class);
        beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);//orderMapper  OrderMapper代理对象
        registry.registerBeanDefinition("orderMapper",beanDefinition1);
     }
}


说明:由于spring扫描方法只能获取扫描类,而不能获取扫描接口。

5.NickelClassPathBeanDefinitionScan通过重写isCandidateComponent方法修饰,实现只能扫描接口

java 复制代码
package com.nq.mybatis.spring;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.classreading.MetadataReader;

import java.io.IOException;
import java.util.Set;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/29 14:31
 */
public class NickelClassPathBeanDefinitionScan extends ClassPathBeanDefinitionScanner {

    //注册对象
    public NickelClassPathBeanDefinitionScan(BeanDefinitionRegistry registry) {
        super(registry);
    }

    /**
     * 获取扫描类是否有值
     * @param basePackages
     * @return
     */
    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        return beanDefinitionHolders;
    }

    /**
     * 判断是否是接口
     * @param beanDefinition
     * @return
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
       return beanDefinition.getMetadata().isInterface();
    }
}


说明:由于spring扫描只会扫描includeFilters里面的类,这里的类指的是类上面加了@Component类才会被扫描到。

6.在NickelClassPathBeanDefinitionScan时候,重写isCandidateComponent(MetadataReader metadataReader)方法,让方法都返回true

1.重写isCandidateComponent方法
java 复制代码
package com.nq.mybatis.spring;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.classreading.MetadataReader;

import java.io.IOException;
import java.util.Set;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/29 14:31
 */
public class NickelClassPathBeanDefinitionScan extends ClassPathBeanDefinitionScanner {

    //注册对象
    public NickelClassPathBeanDefinitionScan(BeanDefinitionRegistry registry) {
        super(registry);
    }

    /**
     * 获取扫描类是否有值
     * @param basePackages
     * @return
     */
    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        return beanDefinitionHolders;
    }

    /**
     * 判断是否是接口
     * @param beanDefinition
     * @return
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
       return beanDefinition.getMetadata().isInterface();
    }

    /**
     * 重新是否包含的接口
     * @param metadataReader
     * @return
     * @throws IOException
     */
    @Override
    protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
        return true;
    }
}
2.修改NickelImportBeanDefinitionRegisty方法
java 复制代码
package com.nq.mybatis.spring;

import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 17:32
 */
public class NickelImportBeanDefinitionRegisty implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        //获取扫描路径
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(NickelMapperScan.class.getName());
        String path = (String)annotationAttributes.get("value");
        System.out.println(path);

        NickelClassPathBeanDefinitionScan scanner=new NickelClassPathBeanDefinitionScan(registry);
        scanner.scan(path);
     }
}
3.修改NickelClassPathBeanDefinitionScan让方法的类都属于NickelFactoryBean对象
java 复制代码
package com.nq.mybatis.spring;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.classreading.MetadataReader;

import java.io.IOException;
import java.util.Set;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/29 14:31
 */
public class NickelClassPathBeanDefinitionScan extends ClassPathBeanDefinitionScanner {

    //注册对象
    public NickelClassPathBeanDefinitionScan(BeanDefinitionRegistry registry) {
        super(registry);
    }

    /**
     * 获取扫描类是否有值
     * @param basePackages
     * @return
     */
    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
            BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition();
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName());
            beanDefinition.setBeanClassName(NickelFactoryBean.class.getName());
        }
        return beanDefinitionHolders;
    }

    /**
     * 判断是否是接口
     * @param beanDefinition
     * @return
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
       return beanDefinition.getMetadata().isInterface();
    }

    /**
     * 重新是否包含的接口
     * @param metadataReader
     * @return
     * @throws IOException
     */
    @Override
    protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
        return true;
    }
}
4.增加MemberMapper.java接口
java 复制代码
package com.nq.mapper;


import org.apache.ibatis.annotations.Select;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 0:24
 */
public interface MemberMapper {

    @Select("select 'user'")
    String selectById();
}
5.修改UserService.java
java 复制代码
package com.nq.service;
import com.nq.mapper.MemberMapper;
import com.nq.mapper.OrderMapper;
import com.nq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:45
 */
@Component
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;

    public void test(){
        System.out.println(userMapper.selectById());
        System.out.println(orderMapper.selectById());
        System.out.println(memberMapper.selectById());
    }

}
6.打印结果显示

结果显示

7.修改NickelFactoryBean代理,使得代理对象为mybatis

1.修改NickelFactoryBean对象
java 复制代码
package com.nq.mybatis.spring;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 16:00
 */
public class NickelFactoryBean implements FactoryBean {

    private Class mapperInterface;

    private SqlSession sqlSession;

    public NickelFactoryBean(Class mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @Autowired
    public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(mapperInterface);
        this.sqlSession = sqlSessionFactory.openSession();
    }

    @Override
    public Object getObject() throws Exception {
        return sqlSession.getMapper(mapperInterface);
    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }
}
2.修改AppConfig配置启动类
java 复制代码
package com.nq.service;

import com.nq.mybatis.spring.NickelImportBeanDefinitionRegisty;
import com.nq.mybatis.spring.NickelMapperScan;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Nickel
 * @version 1.0
 * @date 2023/7/28 14:59
 */
@ComponentScan("com.nq")
@NickelMapperScan("com.nq.mapper")
public class AppConfig {

    @Bean
    public SqlSessionFactory  sqlSessionFactory() throws IOException {
          InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
          SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          return sqlSessionFactory;
    }
}

代码路径:
https://gitee.com/nickel369369/spring-mybatis/mirrors#/

相关推荐
BAGAE34 分钟前
tomcat,appche,nginix,jboss区别
java·linux·数据库·ubuntu·tomcat
uncleqiao40 分钟前
2.mybatis整体配置
mybatis
GGBondlctrl40 分钟前
【Spring MVC】如何获取cookie/session以及响应@RestController的理解,Header的设置
java·spring·mvc·cookie·session·header·restcontroller
大梦百万秋43 分钟前
Spring Boot开发实战:从入门到构建高效应用
java·spring boot
数懒女士1 小时前
Java常见的锁策略
java·算法
大只因bug1 小时前
基于Springboot的流浪宠物管理系统
java·spring boot·mysql·流浪宠物管理系统·在线宠物管理系统源码·javaweb宠物管理系统·宠物网站系统源码
疯一样的码农1 小时前
Maven 如何配置忽略单元测试
java·单元测试·maven
老牛源码1 小时前
Z2400024基于Java+SSM+mysql+maven开发的社区论坛系统的设计与实现(附源码 配置 文档)
java·mysql·maven·ssm
zhangj11251 小时前
Java部分新特性
java·开发语言
暮湫1 小时前
异常处理(6)自定义异常
java