Spring源码之IOC源码深入分析-事务基础阶段IOC源码
前言
工作这么多年,尽忙与业务的增删改查操作,后面发现,对于组件的编写,发现技术的沉淀没有多少。在工作中,避免不了对开源框架的二次开发,然而提起源码二字,脑海中不由的出现恐惧,追根到底,还是对于优秀框架的源码读的太少,于是决定静下心来,再次提起Spring源码的学习。本章节,主要是对Spring IOC 的源码进行回顾,同时,演示代码完全按Spring 事务的结构进行构架,目的也是对Spring 事务源码学习打好基础。其实,对于Spring 源码的学习,核心还是IOC,包括AOP、事务、Spring Boot等都是基于IOC源码的扩展,即基于IOC的二次组件开发。
环境准备
在准备环境前,有必要先看看事务的配置,这块主要是模拟事务源码IOC阶段
配置类:
@Configuration
@ComponentScan("com.xxsc.cn.tx")
//开启事务注解
@EnableTransactionManagement
public class MyConfig {
//配置数据源
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername("****");
dataSource.setPassword("*****");
dataSource.setUrl("jdbc:mysql://localhost:3306/tx-study");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return dataSource;
}
@EnableTransactionManagement
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
//导入TransactionManagementConfigurationSelector组件
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
TransactionManagementConfigurationSelector
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
//AdviceModeImportSelector 继承关系
//AdviceModeImportSelector implements ImportSelector
//spring中导入AutoProxyRegistrar、ProxyTransactionManagementConfiguration 组件
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
return new String[] {
AutoProxyRegistrar.class.getName(),
ProxyTransactionManagementConfiguration.class.getName()};
case ASPECTJ:
return new String[] {
determineTransactionAspectClass()};
default:
return null;
}
}
AutoProxyRegistrar
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
......
//手动导入了 InfrastructureAdvisorAutoProxyCreator
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
......
}
ProxyTransactionManagementConfiguration
首先是一个配置类 ,其次通过@Bean方式向容器中导入了三个bean,只看三个bean即可,省略了其他代码
@Configuration(proxyBeanMethods = false)
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
public BeanFactoryTransactionAttributeSourceAdvisor
@Bean
public TransactionAttributeSource
@Bean
public TransactionInterceptor
}
那么分析到这个地方,关于事务前期的IOC阶段的主要代码都罗列出来了,对于接触过Spring的研发人员都可以猜测出要加入容器中的bean组件吗,结果如下:
1、配置类:myConfig
2、数据源: dataSource
3、@ComponentScan(“com.xxsc.cn.tx”) 扫描下的所有组件
4、@Import 方式继承ImportSelector接口,实现selectImports方法中的返回数据的 autoProxyRegistrar、ProxyTransactionManagementConfiguration 这两个组件
5、autoProxyRegistrar 实现 ImportBeanDefinitionRegistrar 接口手动注册的 InfrastructureAdvisorAutoProxyCreator 组件
6、AbstractTransactionManagementConfiguration 配置类中的@Bean方式添加的三个组件
针对以上事务源码IOC阶段的分析,接下来,模拟这块的应用,彻底的搞清楚这些类在IOC阶段是如何添加到Spring 容器当中的。
配置类
@Configuration
@ComponentScan("com.xxsc.cn.ceshi")
//自定义注解,模拟开启事务
@MyEnableTransction
public