准备工作
1.创建配置类
/**
* @author chinh
* @date 2020/9/17
*/
@Configuration
@ComponentScan("com.chinh")
public class AppConfig {
}
- 创建测试Bean
/**
1. @author chinh
2. @date 2020/9/21
*/
@Service
public class TestServiceImpl implements TestService {
}
- 编写测试代码
/**
* @author chinh
* @date 2020/9/17
*/
public class AnnotationConfigTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
TestService testService = ac.getBean("testServiceImpl", TestService.class);
System.out.println(testService);
}
}
解析启动流程
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
/**
* 隐式调用了父类构造方法: 初始化beanFactory
* super();
*
* 然后才调用自己的构造方法:
*/
this();
/**
* 注册componentClasses
*/
register(componentClasses);
/**
* 刷新上下文
*/
refresh();
}
AnnotationConfigApplicationContext通过父类GenericApplicationContext无参构造初始化父类的成员beanFactory
public GenericApplicationContext() {
/**
* 创建beanFactory
*/
this.beanFactory = new DefaultListableBeanFactory();
}
this()方法执行流程
public AnnotationConfigApplicationContext() {
/**
* 创建一个 AnnotatedBeanDefinitionReader
*/
this.reader = new AnnotatedBeanDefinitionReader(this);
/**
*创建一个 ClassPathDefinitionReader
*/
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
AnnotatedBeanDefinitionReader构造执行流程
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
/**
* getOrCreateEnvironment(如果可能,从给定的注册表中获取环境,否则返回一个新的StandardEnvironment)
*
* 调用重载构造(BeanDefinitionRegistry registry, Environment environment)
*/
this(registry, getOrCreateEnvironment(registry));
}
- getOrCreateEnvironment
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
/**
* AnnotationConfigApplicationContext类一定是EnvironmentCapable
*
* AnnotationConfigApplicationContext
* 继承GenericApplicationContext
* 继承AbstractApplicationContext
* 实现ConfigurableApplicationContext
* 实现ApplicationContext
* 实现EnvironmentCapable
*/
if (registry instanceof EnvironmentCapable) {
//获取 Environment 如果为null默认环境将初始化一个StandardEnvironment
return ((EnvironmentCapable) registry).getEnvironment();
}
return new StandardEnvironment();
}
通过上面注释可以看到getEnvironment的执行逻辑应该在AbstractApplicationContext里面直接把代码贴在下面
@Override
public ConfigurableEnvironment getEnvironment() {
//如果为null 就创建StandardEnvironment
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
2.重载构造(BeanDefinitionRegistry registry, Environment environment)的流程
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
//给registry赋值
this.registry = registry;
/**
* 创建一个ConditionEvaluator
* 初始化成员属性context等于new ConditionContextImpl:
* registry赋值
* 通过registry推断BeanFactory
* 如果environment不为null就赋值 不然就推断
* 如果resourceLoader不为null就赋值 不然就推断
* 通过 resourceLoader和beanFactory推断classLoader
*/
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
/**
* 注册系统的benanProcessors
*/
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
- this.conditionEvaluator = new ConditionEvaluator(registry, environment, null)
public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,
@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
//registry赋值
this.registry = registry;
//通过registry推断BeanFactory
this.beanFactory = deduceBeanFactory(registry);
/**
* 如果environment不为null就赋值 不然就推断
* (在AnnotationConfigApplicationContext里面 通过getOrCreateEnvironment方法初始化了一个StandardEnvironment)
*/
this.environment = (environment != null ? environment : deduceEnvironment(registry));
/**
* 如果resourceLoader不为null就赋值 不然就推断
* (在AnnotationConfigApplicationContext里面是返回自己)
* 因为AnnotationConfigApplicationContext实现了ResourceLoader
*/
this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
/**
* 通过 resourceLoader和beanFactory推断classLoader
* 先从resourceLoader拿 如果没有在beanFactory拿
* 从当前线程拿 从ClassUtils.class拿 返回bootstrap ClassLoader
* 最后是无法访问系统ClassLoader哦,也许调用者可以忍受null ...
*/
this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);
}
到这里主要是初始化AnnotatedBeanDefinitionReader里面的成员属性conditionEvaluator
- AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry)
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
/**
* 在给定的注册表中注册所有相关的注释后处理器。
*/
registerAnnotationConfigProcessors(registry, null);
}
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
//通过registry类型获取BeanFactory
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
/**
* 这里如果是通过AnnotationConfigApplicationContext来启动spring
* 一定是进不来这个判断的因为父类已经初始化好了beanFactory
*/
if (beanFactory != null) {
/**
* 在AnnotationConfigApplicationContext中
* beanFactory为new DefaultListableBeanFactory()
* DependencyComparator就为null 判断为false
* beanFactory设置为AnnotationAwareOrderComparator
*/
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
/**
* 在AnnotationConfigApplicationContext中
* beanFactory为new DefaultListableBeanFactory()
* AutowireCandidateResolver为 new SimpleAutowireCandidateResolver
* SimpleAutowireCandidateResolver不属于ContextAnnotationAutowireCandidateResolver
*/
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
//创建一个 BeanDefinitionHolder Set集合
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
/**
* 查看beanDefinitionMap里面是否有 内部管理的配置注释处理器的Bean
* org.springframework.context.annotation.internalConfigurationAnnotationProcessor
*/
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
//通过ConfigurationClassPostProcessor去构建RootBeanDefinition
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
//AnnotationConfigApplicationContext里面固定传的是null
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/**
* 查看beanDefinitionMap里面是否有 内部管理的配置注释处理器的Bean
* org.springframework.context.annotation.internalAutowiredAnnotationProcessor
*/
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
/**
*
* 检查是否支持JSR-250,如果存在,则添加org.springframework.context.annotation.internalCommonAnnotationProcessor
*/
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/**
* 检查是否支持JPA,如果存在,则添加PersistenceAnnotationBeanPostProcessor。
*/
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
/**
* 查看beanDefinitionMap里面是否有 内部管理的配置注释处理器的Bean
* org.springframework.context.event.internalEventListenerProcessor
*/
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
/**
* 查看beanDefinitionMap里面是否有 内部管理的配置注释处理器的Bean
* org.springframework.context.event.internalEventListenerFactory
*/
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
这里的流程也非常简单就是注册系统配置的benanProcessors
可以看下registerPostProcessor的流程
private static BeanDefinitionHolder registerPostProcessor(
BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
//设置AutowiredAnnotationBeanPostProcessor BeanDefinition的角色为2
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
/**
* 注册BeanDefinition
* 里面代码的执行流程非常长
*/
registry.registerBeanDefinition(beanName, definition);
/**
* 返回一个BeanDefinitionHolder
* 里面封装了BeanDefinition还有对应的beanName
*/
return new BeanDefinitionHolder(definition, beanName);
}
这里注意下系统注册benanProcessors角色设置的是2
ClassPathBeanDefinitionScanner构造执行流程
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
/**
* 调用重载方法,带一个useDefaultFilters为 true
*/
this(registry, true);
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
/**
* getOrCreateEnvironment(如果可能,从给定的注册表中获取环境,否则返回一个新的StandardEnvironment)
*
*/
this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment) {
/**
* AnnotationConfigApplicationContext为ResourceLoader 强转为ResourceLoader
*/
this(registry, useDefaultFilters, environment,
(registry instanceof ResourceLoader ? (ResourceLoader) registry : null));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, @Nullable ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
/**
* AnnotationConfigApplicationContext里面传了true
*/
if (useDefaultFilters) {
registerDefaultFilters();
}
/**
* 赋值environment
* 赋值conditionEvaluator为null
*/
setEnvironment(environment);
setResourceLoader(resourceLoader);
}
1.registerDefaultFilters()执行流程
protected void registerDefaultFilters() {
/**
* 在includeFilters里面新增AnnotationTypeFilter里面annotationType为Component.class
*/
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
/**
* 注册javax.annotation.ManagedBean为AnnotationTypeFilter
* 如果没有找到该类就什么也不做
*/
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
}
/**
* 注册javax.inject.Named为AnnotationTypeFilter
* 如果没有找到该类就什么也不做
*/
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
这里去兼容了JSR-250 javax.annotation.ManagedBean和JSR-330 javax.inject.Named
2.new AnnotationTypeFilter(xxx.class)的执行流程
public AnnotationTypeFilter(Class<? extends Annotation> annotationType) {
this(annotationType, true, false);
}
public AnnotationTypeFilter(
Class<? extends Annotation> annotationType, boolean considerMetaAnnotations, boolean considerInterfaces) {
super(annotationType.isAnnotationPresent(Inherited.class), considerInterfaces);
this.annotationType = annotationType;
this.considerMetaAnnotations = considerMetaAnnotations;
}
这里可以解析出new AnnotationTypeFilter(Component.class)的执行流程
可以知道父类的成员属性为两个false
considerMetaAnnotations为true
如果是这种new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName(“javax.annotation.ManagedBean”, cl)), false)
可以知道父类的成员属性为两个false
considerMetaAnnotations为false
3. setEnvironment(environment)
public void setEnvironment(Environment environment) {
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;
this.conditionEvaluator = null;
}
- setResourceLoader(resourceLoader)
@Override
public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
/**
* AnnotationConfigApplicationContext为ResourcePatternResolver 强转为ResourcePatternResolver
*/
this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
/**
* 如果resourceCaches里面没有MetadataReader就创建一个ConcurrentHashMap Put进去
*/
this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
/**
* 此处为spring5.0的新特性@indexed
* 读取spring.components里面的数量并返回
*/
this.componentsIndex = CandidateComponentsIndexLoader.loadIndex(this.resourcePatternResolver.getClassLoader());
}
4.ResourcePatternUtils.getResourcePatternResolver(resourceLoader)
public static ResourcePatternResolver getResourcePatternResolver(@Nullable ResourceLoader resourceLoader) {
/**
* AnnotationConfigApplicationContext为ResourcePatternResolver 强转为ResourcePatternResolver
*/
if (resourceLoader instanceof ResourcePatternResolver) {
return (ResourcePatternResolver) resourceLoader;
}
else if (resourceLoader != null) {
return new PathMatchingResourcePatternResolver(resourceLoader);
}
else {
return new PathMatchingResourcePatternResolver();
}
}
5.new CachingMetadataReaderFactory(resourceLoader)
public CachingMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
/**
* 不为null 赋值resourceLoader 为null 赋值new DefaultResourceLoader()
*/
super(resourceLoader);
/**
* AnnotationConfigApplicationContext为DefaultResourceLoader
* 应为继承于AbstractApplicationContext
*/
if (resourceLoader instanceof DefaultResourceLoader) {
this.metadataReaderCache =
((DefaultResourceLoader) resourceLoader).getResourceCache(MetadataReader.class);
}
else {
setCacheLimit(DEFAULT_CACHE_LIMIT);
}
}
6.CandidateComponentsIndexLoader.loadIndex(this.resourcePatternResolver.getClassLoader())
@Nullable
public static CandidateComponentsIndex loadIndex(@Nullable ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = CandidateComponentsIndexLoader.class.getClassLoader();
}
//判断缓存里面是否有ClassLoader,没有执行doLoadIndex方法
return cache.computeIfAbsent(classLoaderToUse, CandidateComponentsIndexLoader::doLoadIndex);
}
@Nullable
private static CandidateComponentsIndex doLoadIndex(ClassLoader classLoader) {
if (shouldIgnoreIndex) {
return null;
}
try {
/**
* 获取META-INF/spring.components下面所有的URL
*/
Enumeration<URL> urls = classLoader.getResources(COMPONENTS_RESOURCE_LOCATION);
if (!urls.hasMoreElements()) {
return null;
}
List<Properties> result = new ArrayList<>();
//遍历储存到result里面
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
result.add(properties);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + result.size() + "] index(es)");
}
/**
* 计算出URL的总数量
*/
int totalCount = result.stream().mapToInt(Properties::size).sum();
return (totalCount > 0 ? new CandidateComponentsIndex(result) : null);
}
catch (IOException ex) {
throw new IllegalStateException("Unable to load indexes from location [" +
COMPONENTS_RESOURCE_LOCATION + "]", ex);
}
}