Spring-Mybatis 中的接口为什么可以注入原理 (BeanPostProcessor 后置处理器)

 

 

Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口(也就是本文用的dao层下面的BookMapper)生成代理注入到Spring

 

原理是

Mybatis在与Spring集成的时候可以配置MapperFactoryBean来生成Mapper接口的代理. 例如

 /**
     * dataSource.
     */
    @Bean(name = "dataSource")
    public BasicDataSource dataSource() {
        BasicDataSource dataSource = loadSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    private BasicDataSource loadSource() {
        BasicDataSource dataSourceJira = new BasicDataSource();
        dataSourceJira.setDriverClassName(classname);
        dataSourceJira.setInitialSize(datasourceInitialsize);
        dataSourceJira.setMaxActive(datasourceMaxActive);
        dataSourceJira.setMaxIdle(datasourceMaxIdle);
        dataSourceJira.setMinIdle(datasourceMinIdle);
        dataSourceJira.setMaxWait(datasourceMaxWait);
        dataSourceJira.setMinEvictableIdleTimeMillis(datasourceMinEvicTimemillis);
        dataSourceJira.setTimeBetweenEvictionRunsMillis(datasourceTimeBetweenEvicRunMillis);
        dataSourceJira.setRemoveAbandoned(datasourceRemoveAbandoned);
        dataSourceJira.setRemoveAbandonedTimeout(datasourceRemoveAbandonedTimeout);
        dataSourceJira.setLogAbandoned(datasourceLogAbandoned);
        dataSourceJira.setTestOnBorrow(datasourceTestOnBorrow);
        dataSourceJira.setTestOnReturn(datasourceTestOnReturn);
        dataSourceJira.setTestWhileIdle(datasourceTestwhileIdle);
        dataSourceJira.setValidationQueryTimeout(600);
        return dataSourceJira;
    }

    /**
    sqlSessionFactoryBean
     */
    @Bean(name = "sqlSessionFactoryName")
    @ConditionalOnMissingBean // 当容器里没有指定的Bean的情况下创建该对象
    public SqlSessionFactoryBean sqlSessionFactoryBean(
            @Qualifier("dataSource") BasicDataSource  dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(multipleDataSource);
        // 设置mybatis的主配置文件
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource mybatisConfigXml = resolver.getResource("classpath:spring/sqlmap-config.xml");
        sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
        return sqlSessionFactoryBean;
    }
    
    /**
     * mapper接口的扫描器.
     * @return mapperScannerConfigurer.
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryName");
        mapperScannerConfigurer.setBasePackage("com.davinqi.**.mapper");
        return mapperScannerConfigurer;
    }

Mybatis 创建了  MapperFactoryBean 的代理类实现了  .mapper 接口,并且注入到springBean容器中 。 

 

 

public abstract class SqlSessionDaoSupport extends DaoSupport {
    private SqlSession sqlSession;
    private boolean externalSqlSession;

    public SqlSessionDaoSupport() {
    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        if (!this.externalSqlSession) {
            this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
        }

    }

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSession = sqlSessionTemplate;
        this.externalSqlSession = true;
    }

    public SqlSession getSqlSession() {
        return this.sqlSession;
    }

    protected void checkDaoConfig() {
        Assert.notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
    }
}

 

 public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
        Assert.notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
        Assert.notNull(executorType, "Property 'executorType' is required");
        this.sqlSessionFactory = sqlSessionFactory;
        this.executorType = executorType;
        this.exceptionTranslator = exceptionTranslator;
        this.sqlSessionProxy = (SqlSession)Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[]{SqlSession.class}, new SqlSessionTemplate.SqlSessionInterceptor());
    }

 

看到这: Proxy.newProxyInstance 

大家应该都懂了,他就是使用的Jdk的动态代理。 

 

MyBatis-Spring提供了一个MapperFactoryBean,可以将数据映射接口转为Spring Bean。果数据映射接口很多的话,需要在Spring的配置文件中对数据映射接口做配置,相应的配置项会很多了。

在Service中@Autowired的方法直接注入接口实例。在Spring的配置文件中可以采用以下所示的配置将接口转化为Bean。为了简化配置,在MyBatis-Spring中提供了一个转换器MapperScannerConfig它 继承了 Spring 的 BeanPostProcessor 后置处理器 这样在spring

容器启动时就可以加载Mybatis自动反射实现的类到容器中的Bean了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring-MyBatis整合是一种常见的开发方式,其spring-mybatis.xml文件是用来配置SpringMyBatis框架集成的配置文件。在这个文件,我们会定义数据源、事务管理器、扫描Mapper接口等配置信息。同时,我们还需要将MyBatis的SqlSessionFactory注入Spring容器,以便其他组件可以使用它来执行数据库操作。以下是一个简单的spring-mybatis.xml文件示例: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClass}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 配置SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.example.entity" /> <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml" /> </bean> <!-- 配置Mapper扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启Spring的注解功能 --> <context:annotation-config /> <!-- 开启Spring的AOP功能 --> <aop:aspectj-autoproxy /> <!-- 开启Spring的事务管理功能 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` 在这个配置文件,我们使用了Spring的注解功能、AOP功能和事务管理功能,以及MyBatis的Mapper扫描和SqlSessionFactory配置。其,数据源、事务管理器和Mapper扫描的配置信息需要根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值