自我总结的spring-boot-starter的自动配置原理

spring-boot-starter的自动配置原理

在springboot中

@SpringBootApplication => @EnableAutoConfiguration 开启自动配置

以mybatis为例

1.依赖

 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>  
2.配置文件 data.properties
#server.port=8001
#server.servlet.session.timeout=50M
#spring.datasource.username=root
#spring.datasource.password=root123
#spring.datasource.url=jdbc:mysql://localhost:3306/rocket
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  1. 配置类
    a. 数据源
    b. 事务管理器
    c. SqlSessionFactoryBean

代码如下:

package com.woniuxy.framework.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.IOException;


@Configuration
@ComponentScan("com.woniuxy.framework")
@PropertySource("classpath:app.properties")
@EnableTransactionManagement
@MapperScan("com.woniuxy.framework.dao")//将指定的包下的接口作为mybatis的mapper,注入到spring容器中,并提供实现
public class RootConfig {

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.driverClassName}")
    private String driver;


    //数据源
    @Bean(destroyMethod = "close")
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driver);

        return dataSource;
    }
    //事务
    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }

    /**
     * 配置事务模板
     * @return
     */
    @Bean
    public TransactionTemplate txTemplate(){
        return new TransactionTemplate(transactionManager());
    }


    //sqlSessionFactoryBean配置,替代mybatis-config.xml
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //数据源
        sqlSessionFactoryBean.setDataSource(dataSource());
        //别名包
        sqlSessionFactoryBean.setTypeAliasesPackage("com.woniuxy.framework.model");
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //下划线映射到驼峰
        configuration.setMapUnderscoreToCamelCase(true);
        //日志
        configuration.setLogImpl(StdOutImpl.class);
        sqlSessionFactoryBean.setConfiguration(configuration);

        //配置文件位置
        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = patternResolver.getResources("classpath*:mappers/**/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);

        return sqlSessionFactoryBean;
    }


}

yml代码:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/work8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password:
  mvc:
    format:
      date: yyyy-MM-dd HH:mm:ss
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
mybatis-plus:
  mapper-locations: classpath:mappers/**/*.xml
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
  type-aliases-package: com.woniuxy.boot.mybatisplusdemo.model
logging:
  level:
    org.springframework: info #指定某个包的日志输出为此等级
    com.woniuxy: debug

在springboot中
加入mybatis-spring-boot-starter依赖里面集成例很多spring,mybtais的依赖大大的减少依赖

如图:在这里插入图片描述

原理

扫描,读取 META-INF/spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

定位到自动配置类 ,此处名为MybatisAutoConfiguration

@org.springframework.context.annotation.Configuration 标记此类为配置类
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class) 关联一个配置属性类
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {
    
    
    ....
        
  @Bean//自动配置了SQLSessionFactoryBean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        
        ...
        }

通过自动配置类,定位配置属性类,配置属性类有前缀,能够将外化配置直接转化为Java类的属性

@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)//前缀
// 外化配置的内容与java属性的对应方式,前缀.属性名  mybatis.mapper-location
public class MybatisProperties {

  public static final String MYBATIS_PREFIX = "mybatis";

  private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

  /**
   * Location of MyBatis xml config file.
   */
  private String configLocation;

  /**
   * Locations of MyBatis mapper files.
   */
  private String[] mapperLocations;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值