说明:本章在之前章节《SpringBoot 启动流程源码分析》的基础上继续源码分析。但是本章内容不需要强依赖前面文章,可以单独阅读。
回顾前章
关键源码如下:
public ConfigurableApplicationContext run(String... args) {
// ...省略其它
//配置spring.beaninfo.ignore系统属性
configureIgnoreBeanInfo(environment);
//打印banner.txt
Banner printedBanner = printBanner(environment);
//根据前面webApplicationType值实例化ApplicationContext
//servlet类型实例化的是AnnotationConfigServletWebServerApplicationContext
context = createApplicationContext();
// ...省略其它
} catch (Throwable ex) {
// ...省略其它
}
// ...省略其它
//到这里,整个spring容器加载完毕
return 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:
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);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
webApplicationType的值为SERVLET,所以实例化的上下文类全路径名为:“org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext”,这个类非常重要,它承载Spring IOC加载整个过程需要的能力,下面是这个类继承和实现接口结构图:
首先这个类图可能不看不太清除,但是没有关系,后面会通过文字方式逻辑该类实现的接口以及继承的类说明,这是我们本章重点之一,除此之外本章重点之二是分析AnnotationConfigServletWebServerApplicationContext类实例化构造器的初始化过程。在Spring框架的设计中,每一个接口的定义边界是很清晰的,属性常用的接口作用对于分析Spring框架源码或分析其他跟Spring集成相关的框架都是非常有益的。
下面我们先罗列AnnotationConfigServletWebServerApplicationContext实现相关接口的作用描述:
ResourceLoader接口
接口关键源码:
public interface ResourceLoader {
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
Resource getResource(String location);
@Nullable
ClassLoader getClassLoader();
}
接口说明:
获取资源策略接口,这个接口作用是根据入参路径字符串返回一个Resource,它最核心工作是识别出路径字符串参数是classpath类型资源还是普通URL类型还是文件系统类型的资源,根据判断的类型结果返回不同的Resource实现类。可以猜到Resource接口会有对应资源类型的实现类,Resource接口实现类部分截图如下:
可以看到Resource接口同时继承InputStreamSource接口,代表Resource接口实现类需要实现输入流的转换逻辑,InputStreamSource接口关键源码:
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
至此我们属性了3个接口作用。
BeanFactory接口
接口关键源码:
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
接口说明:
这是访问Spring Bean容器的顶层接口,详细getBean方法大家都比较容易理解。
AutoCloseable接口
接口关键源码:
public interface AutoCloseable {
void close() throws Exception;
}
接口说明:
统一自动关闭资源。
ResourcePatternResolver接口
接口关键源码:
public interface ResourcePatternResolver extends ResourceLoader {
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
Resource[] getResources(String locationPattern) throws IOException;
}
接口说明:
ResourceLoader接口的增强版,支持通过正则路径参数返回Resource数组。
ListableBeanFactory接口
接口关键源码:
public interface ListableBeanFactory extends BeanFactory {
boolean containsBeanDefinition(String beanName);
int getBeanDefinitionCount();
String[] getBeanDefinitionNames();
String[] getBeanNamesForType(ResolvableType type);
...省略其它
}
接口说明:
BeanFactory接口增强版,支持批量获取Bean已经Bean名称数组。
MessageSource接口
接口关键源码:
public interface MessageSource {
@Nullable
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;
}
接口说明:
国际化解析策略接口,通过参数识别返回不同国家语言,注释说明Spring提供了两种现成的实现。
EnvironmentCapable接口
接口关键源码:
public interface EnvironmentCapable {
/**
* Return the {@link Environment} associated with this component.
*/
Environment getEnvironment();
}
接口说明:
获取环境能力接口定义。
HierarchicalBeanFactory接口
接口关键源码:
public interface HierarchicalBeanFactory extends BeanFactory {
@Nullable
BeanFactory getParentBeanFactory();
boolean containsLocalBean(String name);
}
接口说明:
支持多层级BeanFactory接口定义。
ApplicationEventPublisher接口
接口关键源码:
@FunctionalInterface
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {
publishEvent((Object) event);
}
void publishEvent(Object event);
}
接口说明:
发布事件功能接口定义。
Lifecycle接口
接口关键源码:
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
接口说明:
生命周期相关接口定义。
Closeable接口
接口关键源码:
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
接口说明:
IO资源自动关闭接口定义。
ApplicationContext接口
接口关键源码:
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
@Nullable
String getId();
String getApplicationName();
String getDisplayName();
long getStartupDate();
@Nullable
ApplicationContext getParent();
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}
接口说明:
在EnvironmentCapable,
ListableBeanFactory,
HierarchicalBeanFactory,MessageSource,
ApplicationEventPublisher, ResourcePatternResolver接口定义的基础上新增应用上下文相关的接口定义。
AliasRegistry接口
接口关键源码:
public interface AliasRegistry {
void registerAlias(String name, String alias);
void removeAlias(String alias);
boolean isAlias(String name);
String[] getAliases(String name);
}
接口说明:
管理Bean别名接口,提供注册别名,删除别名,获取别名的能力。
ConfigurableApplicationContext接口
接口关键源码:
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
...省略属性
void setId(String id);
void setParent(@Nullable ApplicationContext parent);
void setEnvironment(ConfigurableEnvironment environment);
@Override
ConfigurableEnvironment getEnvironment();
void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);
void addApplicationListener(ApplicationListener<?> listener);
void addProtocolResolver(ProtocolResolver resolver);
void refresh() throws BeansException, IllegalStateException;
void registerShutdownHook();
@Override
void close();
boolean isActive();
ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
}
接口说明:
可配置类型应用上下文接口定义。
WebApplicationContext接口
接口关键源码:
public interface WebApplicationContext extends ApplicationContext {
...省略属性
@Nullable
ServletContext getServletContext();
}
接口说明:
Web Servlet类型应用上下文接口定义。
WebServerApplicationContext接口
接口关键源码:
public interface WebServerApplicationContext extends ApplicationContext {
WebServer getWebServer();
String getServerNamespace();
}
接口说明:
Web Server类型应用上下文接口定义。
BeanDefinitionRegistry接口
接口关键源码:
public interface BeanDefinitionRegistry extends AliasRegistry {
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
boolean containsBeanDefinition(String beanName);
String[] getBeanDefinitionNames();
int getBeanDefinitionCount();
boolean isBeanNameInUse(String beanName);
}
接口说明:
Bean注册接口定义。
ConfigurableWebApplicationContext接口
接口关键源码:
public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {
String APPLICATION_CONTEXT_ID_PREFIX = WebApplicationContext.class.getName() + ":";
String SERVLET_CONFIG_BEAN_NAME = "servletConfig";
void setServletContext(@Nullable ServletContext servletContext);
void setServletConfig(@Nullable ServletConfig servletConfig);
@Nullable
ServletConfig getServletConfig();
void setNamespace(@Nullable String namespace);
@Nullable
String getNamespace();
void setConfigLocation(String configLocation);
void setConfigLocations(String... configLocations);
@Nullable
String[] getConfigLocations();
}
接口说明:
可配置Web类型应用上下文接口定义。
ConfigurableWebServerApplicationContext接口
接口关键源码:
public interface ConfigurableWebServerApplicationContext
extends ConfigurableApplicationContext, WebServerApplicationContext {
void setServerNamespace(String serverNamespace);
}
接口说明:
可配置Web Server类型应用上下文接口定义。
ThemeSource接口
接口关键源码:
public interface ThemeSource {
@Nullable
Theme getTheme(String themeName);
}
接口说明:
主题接口定义。
AnnotationConfigRegistry接口
接口关键源码:
public interface AnnotationConfigRegistry {
void register(Class<?>... annotatedClasses);
void scan(String... basePackages);
}
接口说明:
处理注解配置接口定义。
前面我们介绍完了AnnotationConfigServletWebServerApplicationContext类直接或间接的接口定义。请记住上面介绍的接口只是Spring框架的冰山一角,这里重点是告诉大家了解接口的功能边界是学习Spring框架的技巧之一,后续其它相关的类可以参考这种方式去学习分析。
下面我们看下实现类是怎么设计的,从下面列出可以很方便发现Spring对于接口组合实现上的一些设计规则:
DefaultResourceLoader
AbstractApplicationContext
GenericApplicationContext
GenericWebApplicationContext
ServletWebServerApplicationContext
ServletWebServerApplicationContext
AnnotationConfigServletWebServerApplicationContext
我们总结在Spring框架中接口、抽象类、最终实现类设计思路如下:
1、不同的接口提供单个组件或功能的边界定义。
2、抽象实现类是抽取多个接口通用部分逻辑进行实现,将不通用部分通过定义抽象方法的方式提供给下一层子类去实现。
3、最终实现类实现抽象类特性部分已经其它接口的实现逻辑,已经本身需要包含的逻辑。
AnnotationConfigServletWebServerApplicationContext实例化源码分析
前面我们完整分析了AnnotationConfigServletWebServerApplicationContext类的整个继承和实现,从前面分析中可以看到AnnotationConfigServletWebServerApplicationContext包含的接口基本都是跟Bean和应用类型相关,这也符合Spring框架的核心思想:通过设计Bean的方式简化应用的开发。接下来我们继续分析AnnotationConfigServletWebServerApplicationContext无参构造器实例化过程。
AnnotationConfigServletWebServerApplicationContext构造器源码分析
public class AnnotationConfigServletWebServerApplicationContext
extends ServletWebServerApplicationContext implements AnnotationConfigRegistry {
private final AnnotatedBeanDefinitionReader reader;
private final ClassPathBeanDefinitionScanner scanner;
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
...省略其它
}
无参构造器很清晰地看到,首先实例化了两类解析Bean的解析器,一类是读取注解方式的Bean,另一类是扫码类路径下面的Bean。
AnnotatedBeanDefinitionReader实例化构造器源码分析
public class AnnotatedBeanDefinitionReader {
private final BeanDefinitionRegistry registry;
//实例化Bean名称生成器
private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
//实例化Bean Scope元数据解析器
private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private ConditionEvaluator conditionEvaluator;
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
//getOrCreateEnvironment返回标准环境对象StandardEnvironment
this(registry, getOrCreateEnvironment(registry));
}
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);
//注册内部Processors
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
}
AnnotationConfigUtils.registerAnnotationConfigProcessors(..)源码分析
public abstract class AnnotationConfigUtils {
/**
* The bean name of the internally managed Configuration annotation processor.
*/
public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalConfigurationAnnotationProcessor";
/**
* The bean name of the internally managed BeanNameGenerator for use when processing
* {@link Configuration} classes. Set by {@link AnnotationConfigApplicationContext}
* and {@code AnnotationConfigWebApplicationContext} during bootstrap in order to make
* any custom name generation strategy available to the underlying
* {@link ConfigurationClassPostProcessor}.
* @since 3.1.1
*/
public static final String CONFIGURATION_BEAN_NAME_GENERATOR =
"org.springframework.context.annotation.internalConfigurationBeanNameGenerator";
/**
* The bean name of the internally managed Autowired annotation processor.
*/
public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalAutowiredAnnotationProcessor";
/**
* The bean name of the internally managed Required annotation processor.
* @deprecated as of 5.1, since no Required processor is registered by default anymore
*/
@Deprecated
public static final String REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalRequiredAnnotationProcessor";
/**
* The bean name of the internally managed JSR-250 annotation processor.
*/
public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalCommonAnnotationProcessor";
/**
* The bean name of the internally managed JPA annotation processor.
*/
public static final String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalPersistenceAnnotationProcessor";
private static final String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME =
"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor";
/**
* The bean name of the internally managed @EventListener annotation processor.
*/
public static final String EVENT_LISTENER_PROCESSOR_BEAN_NAME =
"org.springframework.context.event.internalEventListenerProcessor";
/**
* The bean name of the internally managed EventListenerFactory.
*/
public static final String EVENT_LISTENER_FACTORY_BEAN_NAME =
"org.springframework.context.event.internalEventListenerFactory";
private static final boolean jsr250Present;
private static final boolean jpaPresent;
static {
ClassLoader classLoader = AnnotationConfigUtils.class.getClassLoader();
jsr250Present = ClassUtils.isPresent("javax.annotation.Resource", classLoader);
jpaPresent = ClassUtils.isPresent("javax.persistence.EntityManagerFactory", classLoader) &&
ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, classLoader);
}
/**
* Register all relevant annotation post processors in the given registry.
* @param registry the registry to operate on
*/
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
/**
* Register all relevant annotation post processors in the given registry.
* @param registry the registry to operate on
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return a Set of BeanDefinitionHolders, containing all bean definitions
* that have actually been registered by this call
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
//向上转型
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
//配置Order注解排序器
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
//配置Autowire注解解析器
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
//下面的if逻辑基本相同,均为注册内部Processor,这些processor非常重要,相关的核心逻辑在后面文章分析
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
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.
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));
}
// 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));
}
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));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
//BeanDefinition接口是保存解析Bean信息核心对象
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
private static BeanDefinitionHolder registerPostProcessor(
BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
//BeanDefinition.ROLE_INFRASTRUCTURE标示内部使用类型
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(beanName, definition);
return new BeanDefinitionHolder(definition, beanName);
}
@Nullable
private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {
if (registry instanceof DefaultListableBeanFactory) {
return (DefaultListableBeanFactory) registry;
}
else if (registry instanceof GenericApplicationContext) {
return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();
}
else {
return null;
}
}
}
核心逻辑总结:
AnnotatedBeanDefinitionReader类构造器初始化时默认向传入的BeanDefinitionRegistry对象注册了多个Processor已经配置了Order注解的对比器和Autowire注解解析器。
ClassPathBeanDefinitionScanner构造器源码分析
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
private final BeanDefinitionRegistry registry;
private BeanDefinitionDefaults beanDefinitionDefaults = new BeanDefinitionDefaults();
@Nullable
private String[] autowireCandidatePatterns;
private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private boolean includeAnnotationConfig = true;
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
this(registry, true);
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment) {
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;
if (useDefaultFilters) {
//注册注解Component、javax.annotation.ManagedBean、javax.inject.Named过滤器
registerDefaultFilters();
}
setEnvironment(environment);
//初始化资源加载需要的对象
setResourceLoader(resourceLoader);
}
public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
//下面每一个类实例化时在构造器多少都有实现一些初始化属性的逻辑,这块就不一一讲解,后续分析过程再说明
this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
this.componentsIndex = CandidateComponentsIndexLoader.loadIndex(this.resourcePatternResolver.getClassLoader());
}
//这是父类方法
protected void registerDefaultFilters() {
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
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.
}
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.
}
}
}
核心逻辑总结:
主要注册了Bean注解过滤器,后面逻辑这些过滤器对扫描这些注解的Bean非常有用。
AnnotationConfigServletWebServerApplicationContext父类构造器初始化源码分析
为了彻底分析AnnotationConfigServletWebServerApplicationContext实例化过程中还做了哪些逻辑,我们一路往上跟,发下其中父类GenericApplicationContext实例化时new了一个很核心的DefaultListableBeanFactory对象,源码如下:
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
}
光从名字beanFactory就能感受这个对象的重要性,这个对象贯穿整个Bean的加载,但这块的源码分析要到后面的文章逐步去讲解。这里要注意,new DefaultListableBeanFactory对象时初始化了哪些数据:
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Nullable
private static Class<?> javaxInjectProviderClass;
static {
try {
javaxInjectProviderClass =
ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - Provider interface simply not supported then.
javaxInjectProviderClass = null;
}
}
/** Map from serialized id to factory instance. */
private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
new ConcurrentHashMap<>(8);
/** Optional id for this factory, for serialization purposes. */
@Nullable
private String serializationId;
/** Whether to allow re-registration of a different definition with the same name. */
private boolean allowBeanDefinitionOverriding = true;
/** Whether to allow eager class loading even for lazy-init beans. */
private boolean allowEagerClassLoading = true;
/** Optional OrderComparator for dependency Lists and arrays. */
@Nullable
private Comparator<Object> dependencyComparator;
/** Resolver to use for checking if a bean definition is an autowire candidate. */
private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();
/** Map from dependency type to corresponding autowired value. */
private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** Map of singleton and non-singleton bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
/** Map of singleton-only bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
/** List of names of manually registered singletons, in registration order. */
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
/** Cached array of bean definition names in case of frozen configuration. */
@Nullable
private volatile String[] frozenBeanDefinitionNames;
/** Whether bean definition metadata may be cached for all beans. */
private volatile boolean configurationFrozen = false;
/**
* Create a new DefaultListableBeanFactory.
*/
public DefaultListableBeanFactory() {
super();
}
...省略其它
}
AbstractAutowireCapableBeanFactory构造器源码分析
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
/** Strategy for creating bean instances. */
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
/** Resolver strategy for method parameter names. */
@Nullable
private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
/** Whether to automatically try to resolve circular references between beans. */
private boolean allowCircularReferences = true;
/**
* Whether to resort to injecting a raw bean instance in case of circular reference,
* even if the injected bean eventually got wrapped.
*/
private boolean allowRawInjectionDespiteWrapping = false;
/**
* Dependency types to ignore on dependency check and autowire, as Set of
* Class objects: for example, String. Default is none.
*/
private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>();
/**
* Dependency interfaces to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/
private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();
/**
* The name of the currently created bean, for implicit dependency registration
* on getBean etc invocations triggered from a user-specified Supplier callback.
*/
private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");
/** Cache of unfinished FactoryBean instances: FactoryBean name to BeanWrapper. */
private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();
/** Cache of candidate factory methods per factory class. */
private final ConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>();
/** Cache of filtered PropertyDescriptors: bean Class to PropertyDescriptor array. */
private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
new ConcurrentHashMap<>();
/**
* Create a new AbstractAutowireCapableBeanFactory.
*/
public AbstractAutowireCapableBeanFactory() {
super();
//配置忽略给定接口的自动装配
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
...省略其它
}
本章总结:
从本章内容可以看出Spring上下文主要包含BeanFactory、注解解析器、classpath扫描器、以及各个组件相关的其它组合或继承关系的初始化(例如AnnotationConfigUtils#registerAnnotationConfigProcessors),这些初始化的工作为后续IOC加载做好基础组合对象的准备。