Spring学习记录(五):Spring IOC源码学习——基于注解
前言
本来想着基于注解的启动不整理成文章了,后来想到注解是开发的趋势,想了想还是要简单整理一下,相比于之前的配置文件启动来说,在学习完上面的内容,基于注解启动就看起来不要太简单(其实也不简单,只是相比较而言有了基础),先放上之前的一张流程图来!
接着是准备工作也得做一下(这个自己去弄),咱是做转账demo的代码拿出来用用。
首先是目录结构:
config下文件:
package com.ssm.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@PropertySource(value = "classpath:jdbc.properties")
public class DataSourceConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
}
package com.ssm.config;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
@Configuration
@ComponentScan("com.ssm")
@Import(DataSourceConfig.class)
public class SpringConfig {
@Bean("queryRunner")
public QueryRunner getQueryRunner(@Autowired DataSource dataSource){
QueryRunner queryRunner = new QueryRunner(dataSource);
return queryRunner;
}
}
启动项:
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService =
(AccountService) annotationConfigApplicationContext.getBean("accountService");
config下文件:dao、domain之类就不贴了~
一、AnnotationConfigApplicationContext
话不多说直接开搞,断点打好即刻出发~
我们首先进入的第一站就是AnnotationConfigApplicationContext:
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
我们按照步骤,首先看一下第一个this,步入看到简简单单读取器和扫描器:
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
//读取器
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
//扫描器
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
接着走到GenericApplicationContext,这里new了一个beanFactory似曾相识!
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
1.register
接着我们来到方法register,这个其实是注解配置的一个分支,其实还有个scan方法和register类似,因为我们这里走的是启动项写的原因,所以这里不演示scan,有兴趣的可以走一下!当然我们可以猜出来这肯定和包扫描十分的有关系,特别是联想到我们的注解@ComponentScan,我们步入进来看看:
@Override
public void register(Class<?>... componentClasses) {
Assert.notEmpty(componentClasses, "At least one component class must be specified");
StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
.tag("classes", () -> Arrays.toString(componentClasses));
this.reader.register(componentClasses);
registerComponentClass.end();
}
@Override
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
StartupStep scanPackages = this.getApplicationStartup().start("spring.context.base-packages.scan")
.tag("packages", () -> Arrays.toString(basePackages));
this.scanner.scan(basePackages);
scanPackages.end();
}
其实我们这里可以看到这两个结构不能说是一模一样,但是也算是异曲同工了呀!继续前进:
public void register(Class<?>... componentClasses) {
for (Class<?> componentClass : componentClasses) {
registerBean(componentClass);
}
}
public void registerBean(Class<?> beanClass) {
doRegisterBean(beanClass, null, null, null, null);
}
把所有的Bean都给注册下来!
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(supplier);
//得到类的作用域
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
//添加到数据结构结构中
abd.setScope(scopeMetadata.getScopeName());
//生成类的名字
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
//处理一些通用的注解再返回
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
if (customizers != null) {
for (BeanDefinitionCustomizer customizer : customizers) {
customizer.customize(abd);
}
}
//这里 BeanDefinitionHolder 对 BeanDefinition 和 beanName 进行了封装
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
/**
* 把上述的这个数据结构注册给registry
* registy就是AnnotatonConfigApplicationContext
* AnnotatonConfigApplicationContext在初始化的時候通過調用父類的构造方法
* 实例化了一个DefaultListableBeanFactory
* registerBeanDefinition里面就是把definitionHolder这个数据结构包含的信息注册到
* DefaultListableBeanFactory这个工厂
*/
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
接下来走registerBeanDefinition,特别注意这边开始注册Bean了,在走scan的时候最后也是会走这个地方的。
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
//注册bean
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// 这里是别名的注册
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
其实这个地方很熟悉,就是我们在之前走配置文件的时候,在obtainFreshBeanFactory方法中进行doLoad相关的时候就会走到这里,这也是最后注册的一个点,为了方便会议我继续贴代码:
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
//查看是否已存在这个bean
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
//处理重复bean的情况
if (existingDefinition != null) {
//不允许覆盖就抛异常
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// 覆盖自定义bean
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(existingDefinition)) {
//新bean盖旧bean
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
//用同等的bean覆盖旧的
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
//进行覆盖
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
//判断是否有初始化的bean,注册bean结束后其实bean是还没初始化的,在Spring容器启动的最后,会 预初始化 所有的 singleton beans
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// 放入map,这里是所有的BeanDefinition
this.beanDefinitionMap.put(beanName, beanDefinition);
//为了保证顺序建立的ArrayList
this.beanDefinitionNames.add(beanName);
//这里是手动注册的singleton bean 是个链表
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
特别需要注意的是,此时配置类, 并没有被创建出来, 只是解析了一番, 相当于是给 spring 写了一份说明。 后面 spring 会根据这份说明,来创建和解析配置类。
2.refresh
走完之后我们又回到了特别属性第二个方法——refresh。这个方法和前面的配置文件版本的一模一样并没有任何区别(毕竟调用的是同一个嘛),但还是要贴出来看一下:
@Override
public void refresh() throws BeansException, IllegalStateException {
//加锁防止refresh还没结束,容器又进行其他操作
synchronized (this.startupShutdownMonitor) {
//进行准备工作,记录容器的启动时间并标记启动状态以及处理配置文件中的占位符
prepareRefresh();
//这里会把配置文件解析出一个个bean出来,但是还没有初始化
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//设置 BeanFactory 的类加载器
prepareBeanFactory(beanFactory);
try {
// 提供了一些拓展的方式,这边还是很牛的
postProcessBeanFactory(beanFactory);
//调用BeanFactoryPostProcessor各个实现类的postProcessBeanFactory(factory)方法
invokeBeanFactoryPostProcessors(beanFactory);
// 注册
registerBeanPostProcessors(beanFactory);
//初始化当前ApplicationContext的MessageSource
initMessageSource();
// 初始化当前ApplicationContext的事件广播器
initApplicationEventMulticaster();
// 钩子方法
onRefresh();
// 注册事件监听器,监听器需要实现ApplicationListener接口
registerListeners();
//初始化所有的singleton beans
finishBeanFactoryInitialization(beanFactory);
// 广播
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
但是他和之前还是有不一样的地方,在于obtainFreshBeanFactory,我们之前已经通过register解析出了bean,所以在这里我们步入这个方法的时候我变得异常简洁:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}
没错就这么点,毕竟人家也没啥事情需要他做了。
总结
剩下的也没啥事情做了,初始化的工作和前文一模一样,大家可以回去再看一下,虽然说的一般般。