createApplicationContext()实例AnnotationConfigServletWebServerApplicationContext
Posted ppjj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了createApplicationContext()实例AnnotationConfigServletWebServerApplicationContext相关的知识,希望对你有一定的参考价值。
目录
1. 创建应用上下文
2. DefaultResourceLoader
3. AbstractApplicationContext
4. GenericApplicationContext
4.1 SimpleAliasRegistry
4.2 DefaultSingletonBeanRegistry
4.3 FactoryBeanRegistrySupport
4.4 AbstractBeanFactory
4.5 AbstractAutowireCapableBeanFactory
4.6 DefaultListableBeanFactory
4.1 SimpleAliasRegistry
5. GenericWebApplicationContext
6. ServletWebServerApplicationContext
7.AnnotationConfigServletWebServerApplicationContext
7.1 AnnotatedBeanDefinitionReader
7.2 ClassPathBeanDefinitionScanner
8. 总结
1. 创建应用上下文
在初始化SpringApplication实例中, 已经分析了当前模块web类型为SERVLET, 所以当前实例化了一个AnnotationConfigServletWebServerApplicationContext对象
public class SpringApplication {
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//应用上下文
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
//本文的重点
//创建应用上下文
//AnnotationConfigServletWebServerApplicationContext
context = createApplicationContext();
//...
}
public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
+ "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
//创建应用上下文
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
//我们使用的是servlet web环境
//实例化AnnotationConfigServletWebServerApplicationContext对象
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
//返回的是一个AnnotationConfigServletWebServerApplicationContext对象
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
}
由上面类图,我们可以看出, 类继承关系如下:
- AnnotationConfigServletWebServerApplicationContext类继承了ServletWebServerApplicationContext
- ServletWebServerApplicationContext继承了GenericWebApplicationContext
- GenericWebApplicationContext继承了GenericApplicationContext
- GenericApplicationContext继承了AbstractApplicationContext
- AbstractApplicationContext继承了DefaultResourceLoader
2. DefaultResourceLoader
用来加载Resource, 初始化的过程中, 实例化了ClassLoader,
//默认的资源加载器
public class DefaultResourceLoader implements ResourceLoader {
@Nullable
private ClassLoader classLoader;
//自定义ProtocolResolver, 用于获取资源
private final Set<ProtocolResolver> protocolResolvers = new LinkedHashSet<>(4);
//
private final Map<Class<?>, Map<Resource, ?>> resourceCaches = new ConcurrentHashMap<>(4);
//实例化ClassLoader
public DefaultResourceLoader() {
this.classLoader = ClassUtils.getDefaultClassLoader();
}
//加载资源
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
//自定义资源加载方式
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
//调用ProtocolResolver的resolve方法
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
//如果获取到资源,立即返回
return resource;
}
}
if (location.startsWith("/")) {
//先判断是否是根目录
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
//再判断是否是classpath下的资源
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
//先当做一个URL处理
URL url = new URL(location);
//先判断是否是一个file
//不是file的话,再从URL中获取
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
//获取不到资源的话
//当做resource处理
return getResourceByPath(location);
}
}
}
}
3. AbstractApplicationContext
抽象ApplicationContext, 定义了ApplicationContext一些模板方法, 在实例化的过程中, 调用了getResourcePatternResolver()方法, 构造了一个PathMatchingResourcePatternResolver, 规定了如何查找资源, 例如从classpath, 根路径, 从war包等查找资源
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
private ResourcePatternResolver resourcePatternResolver;
//初始化一个resourcePatternResolver
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
//该方法被GenericWebApplicationContext类重写
//实际调用的是GenericWebApplicationContext的getResourcePatternResolver()方法
protected ResourcePatternResolver getResourcePatternResolver() {
//this实现了DefaultResourceLoader
//可以作为PathMatchingResourcePatternResolver构造函数的参数
return new PathMatchingResourcePatternResolver(this);
}
}
4. GenericApplicationContext
初始化了一个DefaultListableBeanFactory
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
//初始化beanFactory
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
}
由上面类图, 我们可以看出DefaultListableBeanFactory的继承关系:
- DefaultListableBeanFactory继承了AbstractAutowireCapableBeanFactory
- AbstractAutowireCapableBeanFactory继承了AbstractBeanFactory
- AbstractBeanFactory继承了FactoryBeanRegistrySupport
- FactoryBeanRegistrySupport继承了DefaultSingletonBeanRegistry
- DefaultSingletonBeanRegistry继承了SimpleAliasRegistry
4.1 SimpleAliasRegistry
提供了bean别名的增删改查功能
public class SimpleAliasRegistry implements AliasRegistry {
//key是bean别名
//value是原始bean名称
private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);
}
4.2 DefaultSingletonBeanRegistry
默认的单例Bean注册器, 提供了单例bean增删改查等功能
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
//缓存单例bean, key为bean名称,value为bean实例
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
//缓存beanFactory, key为bean名称,value为beanFactory
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
//早期单例缓存, key为bean名称,value为bean实例
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
//单例bean名称set
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
//正在创建的单例bean名称set
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
//当前在创建检查中排除的bean名称set
private final Set<String> inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
//异常set
@Nullable
private Set<Exception> suppressedExceptions;
//正在销毁的bean名称set
private boolean singletonsCurrentlyInDestruction = false;
//一次性的bean实例
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
//bean包含关系map, key为bean名称, value为被包含的bean名称
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
//bean依赖关系缓存, key为bean名称,value为依赖该bean的bean名称
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
//bean依赖关系缓存,key为bean名称,value为该bean依赖的bean名称
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
}
4.3 FactoryBeanRegistrySupport
提供了FactoryBean的增删改查方法
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
//缓存FactoryBean单例的Map
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
}
4.4 AbstractBeanFactory
抽象BeanFactory, 定义了通用的beanFactory的模板方法, 添加了对beanFactory对Scope的支持, scope主要有五种, singleton, prototype, request, session和application,
- ConfigurableBeanFactory定义两个SCOPE
- SCOPE_SINGLETON = "singleton"
- SCOPE_PROTOTYPE = "prototype"
- WebApplicationContext接口中定义了三个SCOPE
- SCOPE_REQUEST = "request"
- SCOPE_SESSION = "session"
- SCOPE_APPLICATION = "application"
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
//自定义PropertyEditorRegistrar属性编辑器注册器
//用于编辑Factory下的所有bean
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);
//自定义PropertyEditor属性编辑器
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);
//String值解析器
private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();
//Bean创建处理器
private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
//Bean Scope范围支持
//父接口ConfigurableBeanFactory中定义了两个SCOPE
//SCOPE_SINGLETON = "singleton";
//SCOPE_PROTOTYPE = "prototype";
//WebApplicationContext接口中定义了三个SCOPE
//SCOPE_REQUEST = "request";
//SCOPE_SESSION = "session";
//SCOPE_APPLICATION = "application"
private final Map<String, Scope> scopes = new LinkedHashMap<>(8);
}
4.5 AbstractAutowireCapableBeanFactory
抽象自动配置BeanFactory, 实现了创建Bean, 实例化Bean, 字段配置Bean, 自动装配依赖Bean的方法
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
//创建Bean策略,默认为cglib
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
public AbstractAutowireCapableBeanFactory() {
//显示调用父类方法
super();
//自动装配忽略BeanNameAware接口
ignoreDependencyInterface(BeanNameAware.class);
//自动装配忽略BeanFactoryAware接口
ignoreDependencyInterface(BeanFactoryAware.class);
//自动装配忽略BeanClassLoaderAware接口
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
}
4.6 DefaultListableBeanFactory
BeanFactory默认实现, spring IOC默认容器类
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
//key为依赖类型, value为自动配置的值
private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);
//key为bean名称, value为bean定义
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
//key为依赖的类型, value为所有bean名称列表
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
//key为依赖类型, value为单例bean的名称数组
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
//按注册的顺序, 记录的bean名称列表
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
//手动添加的bean名称列表
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
public DefaultListableBeanFactory() {
//显示调用父类构造函数
super();
}
}
5. GenericWebApplicationContext
重写了AbstractApplicationContext的getResourcePatternResolver()方法, 返回一个ServletContextResourcePatternResolver对象, 构造函数中显示调用父类GenericApplicationContext的构造函数
public class GenericWebApplicationContext extends GenericApplicationContext
implements ConfigurableWebApplicationContext, ThemeSource {
//显式调用父GenericApplicationContext类构造方法
//什么都不做
public GenericWebApplicationContext() {
super();
}
//ServletContextResourcePatternResolver
//重写了父类获取资源的逻辑
//从ServletContext中获取资源
@Override
protected ResourcePatternResolver getResourcePatternResolver() {
return new ServletContextResourcePatternResolver(this);
}
}
6. ServletWebServerApplicationContext
隐式调用父类GenericWebApplicationContext构造函数, 什么都没有做
public class ServletWebServerApplicationContext extends GenericWebApplicationContext
implements ConfigurableWebServerApplicationContext {
//什么都不做
//隐式调用父类GenericWebApplicationContext构造方法
public ServletWebServerApplicationContext() {
}
}
7.AnnotationConfigServletWebServerApplicationContext
首先, 初始化一个AnnotatedBeanDefinitionReader, 然后再实例化一个ClassPathBeanDefinitionScanner对象
//注解配置ServletWeb服务应用上下文
//当前SpringApplication上下文
public class AnnotationConfigServletWebServerApplicationContext
extends ServletWebServerApplicationContext implements AnnotationConfigRegistry {
//注解Bean读取器,用来去取bean
private final AnnotatedBeanDefinitionReader reader;
//ClassPath中的Bean扫描器,用来扫描bean
private final ClassPathBeanDefinitionScanner scanner;
//被注册到容器中的Class对象列表
private final Set<Class<?>> annotatedClasses = new LinkedHashSet<>();
//需要扫描的包
private String[] basePackages;
//构造函数
public AnnotationConfigServletWebServerApplicationContext() {
//注解Bean读取器 传入this
this.reader = new AnnotatedBeanDefinitionReader(this);
//Classpath中的Bean扫描器
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
}
7.1 AnnotatedBeanDefinitionReader();
用于读取和解析bean定义
//注解Bean读取器
//用来读取和解析bean
public class AnnotatedBeanDefinitionReader {
private final BeanDefinitionRegistry registry;
//bean名称生成器
private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
//Scope解析器
private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private ConditionEvaluator conditionEvaluator;
//registry传入的AnnotationConfigServletWebServerApplicationContext对象
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
//构造函数
//传入的registry就是AnnotationConfigServletWebServerApplicationContext实例
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
//条件评估器的初始化
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
//注解配置注册器
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
//获取或创建环境
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry instanceof EnvironmentCapable) {
//实现了EnvironmentCapable
//调用了AbstractApplicationContext中的getEnvironment方法
//获取到了StandardEnvironment实例
return ((EnvironmentCapable) registry).getEnvironment();
}
return new StandardEnvironment();
}
}
AnnotationBeanNameGenerator
注解bean名称生成器, 用于生成Bean名称
//bean名称生成器
//主要为Component注解生成名称
//包括Component子注解: Component,Respository,Service,Controller
//还包括java6的ManagedBean
public class AnnotationBeanNameGenerator implements BeanNameGenerator {
//Spring Component注解
private static final String COMPONENT_ANNOTATION_CLASSNAME = "org.springframework.stereotype.Component";
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
//如果是注解的bean定义
if (definition instanceof AnnotatedBeanDefinition) {
//先从注解获取bean名称
String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
//不为空直接返回
if (StringUtils.hasText(beanName)) {
return beanName;
}
}
//注解没有定义bean名称,那么构造一个bean名称
return buildDefaultBeanName(definition, registry);
}
/**
* 构造bean名称
*/
protected String buildDefaultBeanName(BeanDefinition definition) {
String beanClassName = definition.getBeanClassName();
Assert.state(beanClassName != null, "No bean class name set");
//获取Class名称
String shortClassName = ClassUtils.getShortName(beanClassName);
//将类名作为bean名称
return Introspector.decapitalize(shortClassName);
}
}
public class Introspector {
public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
//如果第一个和第二个字符都是大写,直接返回名称
return name;
}
//将第一个字符转换为小写,返回类名
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
}
AnnotationScopeMetadataResolver
Scope注解的解析器, 解析出Scope的模式ScopedProxyMode, 以及Scope的名称
//@Scope注解的解析器
public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
//Scope注解
protected Class<? extends Annotation> scopeAnnotationType = Scope.class;
//代理模式
private final ScopedProxyMode defaultProxyMode;
//默认不使用代理
public AnnotationScopeMetadataResolver() {
this.defaultProxyMode = ScopedProxyMode.NO;
}
//解析@Scope注解
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
//注解bean
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition)definition;
//获取到metadata放入名为attributes的map中
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(annDef.getMetadata(), this.scopeAnnotationType);
if (attributes != null) {
//将@Scope注解的value和proxyMode放入到metadata中
metadata.setScopeName(attributes.getString("value"));
ScopedProxyMode proxyMode = (ScopedProxyMode)attributes.getEnum("proxyMode");
if (proxyMode == ScopedProxyMode.DEFAULT) {
proxyMode = this.defaultProxyMode;
}
metadata.setScopedProxyMode(proxyMode);
}
}
return metadata;
}
}
//代理模式枚举
public enum ScopedProxyMode {
//默认代理模式,默认使NO,
//如果在component-scan中配置了默认值,将会使用这个默认值
DEFAULT,
//不使用代理
NO,
//接口,使用jdk动态代理
INTERFACES,
//类,使用cglib动态代理
TARGET_CLASS;
}
ConditionEvaluator
@Conditional注解的条件评估器, 评估是否满足条件
//@Conditional注解的解析器
//也可用于@ConditionalOnBean,@ConditionalOnClass,@ConditionalOnExpression,@ConditionalOnMissingBean等子注解
class ConditionEvaluator {
//内部类
private final ConditionContextImpl context;
//构造函数
public ConditionEvaluator(@Nullable BeanDefinitionRegistry registry,
@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
this.context = new ConditionContextImpl(registry, environment, resourceLoader);
}
//判断是否应该跳过
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
//metadata为空或者没有使用@Conditional注解,不跳过
return false;
}
if (phase == null) {
//ConfigurationPhase对象为空,也就是没有设置生效条件
if (metadata instanceof AnnotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
//如果是注解的话,使用PARSE_CONFIGURATION配置验证是否跳过
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
//不是注解的话,使用REGISTER_BEAN配置验证是否跳过
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List<Condition> conditions = new ArrayList<>();
//遍历配置类的条件注解,得到条件数据,放到conditions集合中
for (String[] conditionClasses : getConditionClasses(metadata)) {
for (String conditionClass : conditionClasses) {
Condition condition = getCondition(conditionClass, this.context.getClassLoader());
conditions.add(condition);
}
}
//按Order注解排序
AnnotationAwareOrderComparator.sort(conditions);
//条件排序
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
}
//添加验证满足,那就跳过
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
return true;
}
}
return false;
}
//私有静态内部类
private static class ConditionContextImpl implements ConditionContext {
public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,
@Nullable