Bean解析
一、IOC思想
1.IOC思想
如下图我们有四个零件来保证我们装置的正常运行,换成Java的语言表达就是四个对象,ObjectA依赖ObjectB,ObjectB依赖ObjectC,ObjectC依赖ObjectD,通过这样的协作关系来完成我们程序的运行,这样子就需要我们在一个类中定义另外一个类,早些的时候我们是手动new一个对象出现
2.举例说明
假设有一个animal类有两个实现Dog和Cat,如果我们要使用Dog就需要在我们的类里直接new一个Dog出来,但是之后我们突然要将我们的动物改成Cat,就需要再类中将我们的Animal改成new Cat();,这样子的操作会给我们带来不便,而且耦合度太高;我们使用Spring会将对象直接注入到Spring的IOC容器中,而不用关心他的具体实现
Aniaml animal = new Dog();
Aniaml animal = new Cat();
@Autowired
Aniaml animal;
3.总结
我们使用了一个容器将四个装置隔离开了,使用容器来管理他们,不需要每个类知道对方的存在,通过中间的容器来带动装置正常运行,
优点:
1.松耦合:之前每个类都要明确的感知到对方的存在,紧紧的耦合在一起,现在通过容器来控制降低了耦合想
2.灵活性:不需要在类中调用使用类的构造方法来去构造一个实例,而是通过我们容器完成构造,注入到我们需要的类中
3.可维护性:之前我们不能明确那些地方使用了Animal类,需要一个个去寻找,
二、Bean的配置方式
1.xml方式配置Bean介绍
一、无参构造
需要在Spring的类中加入一个无参构造方法,如下图
二、有参构造
需要在Spring的类中加入一个有参构造方法,如下图
三、静态工厂方法
我们定义了一个AnimalFactory工厂类,在工厂类中我没有一个getAnimal方法,通过传入不同的type值返回不同的对象
四、实例工厂方法
我们将AnimalFactory工厂类的getAnimal方法改成一个实例方法,这个就需要我么先将AnimalFactory工厂类添加到我们的容器当中在注册dog和cat的时候就指明我们的factory-bean是哪一个
五、总结
1.低耦合:由容器来完成对应类的注入
2.对象关系清晰:通过xml文件清楚知道哪些类之前由依赖关系
3.集中管理:可以在xml中集中管理,方便删除和添加
六、缺点
1.配置繁琐
2.开放效率低
3.文件解析耗时
2.注解
一、@Component声明
直接在类上加上@Component注解来完成Bean的注入
二、配置类中使用@Bean
定义了一个配置类,在里面书写了一个方法返回Animal类,并在方法上添加上@Bean的注解,完成Bean的注入
三、继承FactoryBean
通过实现FactoryBean这个接口来完成的,定义了一个MyCat实现FactoryBean,在getObect方法中返回Cat类即可
四、继承BeanDefinitionRgistryPostProcessor
创建了MyBeanRegister类实现了BeanDefinitionRgistryPostProcessor,重写了postProcessBeanDefinitionRegistry方法,在里面新建了BeanDefinition定义,然后将这个定义注册到了我们容器当中
五、继承ImportBeanDefinitionRegistrar
创建了MyBeanImport类实现ImportBeanDefinitionRegistrar,重写了registerBeanDefinitions方法
六、总结
1.使用注解方式的优点
①使用简单:直接使用一个注解就ok了
②开发效率高:不用书写什么配置文件
③高内聚:一个类的定义和注解是维护在同一个文件类中的,不会分散开来
2.使用注解方式的缺点
①配置分散:不会像xml那样配置都集中在一个文件当中,方便查看
②对象关系不清晰:不像xml那样清晰,引用在文件中就可以看到
③配置修改需要重新编译工程
三、Refresh方法解析
一、Bean配置读取加载入口
1.方法步骤
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 在我们刷新上下文之前做一个准备
prepareRefresh();// 该方法是一个同步方法
// Tell the subclass to refresh the internal bean factory.
// 获取Bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 对BeanFactory做一些配置,包括他的各种类加载器,需要忽略的依赖,以及后处理器解析器等等
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 注册web请求相关处理器和Bean以及配置
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 调用在上下文中注册为bean的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 该方法是在factory当中bean实例化完成之后再去对bean进行处理,他的调用是在bean实例化之后调用,所以并不需要调用BeanPostProcessors的实现类对bean的后续处理方法,只是将其添加到beanFactory当中
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
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();
}
}
}
// prepareRefresh方法
protected void prepareRefresh() {
// 判断是否存在缓存,如果存在调用clearCache方法来清楚缓存
this.scanner.clearCache();
super.prepareRefresh();
}
// clearCache方法
public void clearCache() {
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
protected void prepareRefresh() {
// Switch to active.
// 记录当前时刻,即启动时间
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
// 当前上下文处于Activce的状态
this.active.set(true);
// 如果当前日志是Debug模式的话,就会往下执行
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 在上下文环境中初始化属性
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 检测我们是否设置了必备属性值,如果必备属性值不存在就会报错
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
// 会判断系统监听器(earlyApplicationListeners )是否为空,如果为空就将系统中的系统监听器赋给它
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 初始化earlyApplicationEvents 属性
this.earlyApplicationEvents = new LinkedHashSet<>();
}
/**
* <p>Replace any stub property sources with actual instances.
* @see org.springframework.core.env.PropertySource.StubPropertySource
* @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
*/
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
// initPropertySources方法
protected void initPropertySources() {
// 获取环境的上下文
ConfigurableEnvironment env = this.getEnvironment();
// 如果我们的环境属于一个web配置环境
if (env instanceof ConfigurableWebEnvironment) {
// 将servletContext和ServletConfig这两个实现配置加载到环境中
((ConfigurableWebEnvironment)env).initPropertySources(this.servletContext, (ServletConfig)null);
}
}
// obtainFreshBeanFactory方法
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 设置属性和设置beanFactory的序列化ID
refreshBeanFactory();
// 获取到的beanFactory属性(DefaultListableBeanFactory),之后会将其返回给refresh方法体内的beanFactory属性
return getBeanFactory();
}
// refreshBeanFactory
protected final void refreshBeanFactory() throws IllegalStateException {
//设置refreshed属性,标明我们已经在刷新
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
// 给beanFactory设置一个序列化ID,默认是application
this.beanFactory.setSerializationId(getId());
}
// prepareBeanFactory方法
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 给BeanFactory设置一个类加载器
beanFactory.setBeanClassLoader(getClassLoader());
// 设置一个解析器,用来解析SPL表达式的
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 图片转化的时候使用
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// Bean的后置处理器
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 忽略这个自动装配的接口,之后会交给ApplicationContextAwareProcessor来处理
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 添加一个解析依赖,检查自身
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
// 添加一个解析依赖,检查自身
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
// 添加一个解析依赖,检查自身beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
// 添加一个解析依赖,检查自身
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// Bean的Post处理器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 判断系统中是否包含loadTimeWeaver,如果包含就会像系统中设置BeanPostProcessor,以及一个临时的ClassLoader
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
// 判断系统中是否包含environment,如果不包含就向系统中注册environment这个Bean
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
// 判断系统中是否包含systemProperties,如果不包含就向系统中注册systemProperties这个Bean
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
// 判断系统中是否包含systemEnvironment,如果不包含就向系统中注册systemEnvironment这个Bean
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
// postProcessBeanFactory方法
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 调用父类的方法
super.postProcessBeanFactory(beanFactory);
// 判断basePackages 是否为null
if (this.basePackages != null && this.basePackages.length > 0) {
this.scanner.scan(this.basePackages);
}
// 判断annotatedClasses是否为null
if (!this.annotatedClasses.isEmpty()) {
this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
}
}
// postProcessBeanFactory方法
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 向BeanFactory添加后置处理器
beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
// 增加忽略的装配处理接口ServletContextAware
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
// 注册web应用的作用域和环境的配置信息
registerWebApplicationScopes();
}
// registerWebApplicationScopes方法
private void registerWebApplicationScopes() {
//
ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes(getBeanFactory());
WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory());
existingScopes.restore();
}
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) {
registerWebApplicationScopes(beanFactory, null);
}
// registerWebApplicationScopes方法
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
@Nullable ServletContext sc) {
// 向BeanFactory中注册作用域,如request和session
beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
if (sc != null) {
ServletContextScope appScope = new ServletContextScope(sc);
beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
// Register as ServletContext attribute, for ContextCleanupListener to detect it.
sc.setAttribute(ServletContextScope.class.getName(), appScope);
}
// 向BeanFactory中注册解析依赖如ServletRequest和HttpSession
beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
if (jsfPresent) {
FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
}
}
// invokeBeanFactoryPostProcessors方法
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 调用getBeanFactoryPostProcessors方法返回的PostProcessors会进入invokeBeanFactoryPostProcessors方法体内
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
// 判断beanFactory是否包含loadTimeWeaver,不包含直接返回
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
// getBeanFactoryPostProcessors方法
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
// 返回当前上下文中的beanFactoryPostProcessors实现,如图-1,得到上述的PostProcessors之后返回
return this.beanFactoryPostProcessors;
}
// 向我们应用上下文中添加PostProcessor(beanFactoryPostProcessors也是通过这个方法来添加其对应的实现的),他会在初始化和监听器中被调用如图-2
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
// 在ConfigFileApplicationListener监听器中调用addBeanFactoryPostProcessor
protected void addPostProcessors(ConfigurableApplicationContext context) {
context.addBeanFactoryPostProcessor(new PropertySourceOrderingPostProcessor(context));
}
// onApplicationPreparedEvent调用addPostProcessors,再见听到我们环境准备好之后会向我们系统中添加PostProcessors
private void onApplicationPreparedEvent(ApplicationEvent event) {
this.logger.switchTo(ConfigFileApplicationListener.class);
addPostProcessors(((ApplicationPreparedEvent) event).getApplicationContext());
}
// 在初始化器ConfigurationWarningsApplicationContextInitializer中调用addBeanFactoryPostProcessor
public void initialize(ConfigurableApplicationContext context) {
// 在初始化的时候向我们的上下文中BeanFactoryPostProcessor
context.addBeanFactoryPostProcessor(new ConfigurationWarningsPostProcessor(getChecks()));
}
// invokeBeanFactoryPostProcessors方法
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
// 判断BeanFactory是不是BeanDefinitionRegistry的实现类,如果是就往下执行
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 构造两个集合
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 遍历我们处理的beanFactoryPostProcessors
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//判断 postProcessor 是否是BeanDefinitionRegistryPostProcessor的实现类,如果是的话,将往下执行,并将结果registryProcessor存入到registryProcessor集合当中,否则就添加到regularPostProcessors集合中
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
//通过实现postProcessBeanDefinitionRegistry方法,可可以向我们的BeanFactory当中添加一些Bean的定义
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 获取所有的BeanDefinitionRegistryPostProcessor的实现
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 对postProcessorNames进行遍历,如果这个类实现了PriorityOrdered接口,便会把他加入到currentRegistryProcessors集合当中并添加到processedBeans集合当中
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 对两个集合做一个排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 将currentRegistryProcessors添加到registryProcessors集合当中
registryProcessors.addAll(currentRegistryProcessors);
// 调用invokeBeanDefinitionRegistryPostProcessors方法执行postProcessors中的每个postProcessBeanFactory方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空currentRegistryProcessors
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 下面的操作和上面的一致,获取-》排序-》操作-》清空
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 判断如果有类实现了BeanDefinitionRegistryPostProcessor这个接口,reiterate 就会赋值为true接着进行循环,将新属性注入容器中,直到在新的一次遍历中没有发现不存在没有处理过的类,也就是说我们没有通过实现BeanDefinitionRegistryPostProcessor这个接口这个类往BeanFactory中添加新的BeanDefinitionRegistryPostProcessor的实现类,就认为我们不在需要处理该接口的实现类了跳出该循环
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!//
//获取 beanFactory当中的BeanFactoryPostProcessor的实现
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 遍历所有的实现类
for (String ppName : postProcessorNames) {
//判断其是否已经被处理过了
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
// 未被处理过的话,就判断是否实现了PriorityOrdered接口,如果实现了就添加到priorityOrderedPostProcessors集合当中
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
// 接着判断是否实现了Ordered接口,如果实现了就会添加到
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
// 否则就会添加到nonOrderedPostProcessorNames这个集合当中
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 下面的操作都是对结合进行排序,之后调用invokeBeanFactoryPostProcessors方法依次调用postProcessor的postProcessBeanFactory方法
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 清除上面步骤产生的缓存
beanFactory.clearMetadataCache();
}
// invokeBeanFactoryPostProcessors方法
private static void invokeBeanFactoryPostProcessors(
Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
// registerBeanPostProcessors方法
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// registerBeanPostProcessors方法,是在factory当中bean实例化完成之后再去对bean进行处理,他的调用是在bean实例化之后调用,所以并不需要调用BeanPostProcessors的实现类对bean的后续处理方法,只是将其添加到beanFactory当中
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
// registerBeanPostProcessors方法
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 获取beanFactory中的BeanPostProcessor的实现
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
// 向beanFactory中添加BeanPostProcessor实现
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 遍历所有的postProcessor
for (String ppName : postProcessorNames) {
// 如果当前的实现类实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 就会将其放入到priorityOrderedPostProcessors集合当中
priorityOrderedPostProcessors.add(pp);
// 再判断他如果是MergedBeanDefinitionPostProcessor的实现类,就会将其加入internalPostProcessors集合当中
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
//否则的话就判断该实现类是否实现了Ordered接口,是的话就添加到orderedPostProcessorNames集合当中
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
// 都不是的话就添加到nonOrderedPostProcessorNames集合当中
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 对上面的集合进行排序,由于nonOrderedPostProcessorNames集合中的实现类为实现Ordered接口所以不需要排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 并添加到beanFactory当中
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 将beanPostProcessor添加到beanFactory当中
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
this.beanPostProcessors.add(beanPostProcessor);
}
// registerBeanPostProcessors方法
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
// 添加操作
beanFactory.addBeanPostProcessor(postProcessor);
}
}
// addBeanPostProcessor方法(先移除在进行添加,保证不会在同一个beanFactory当中出现两个同样的beanPostProcessor的实现)
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove// from old position, if any
// 将当前的实现从beanPostProcessors当中移除
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
// 再进行添加,不会出现重复出现的问题
this.beanPostProcessors.add(beanPostProcessor);
}
initMessageSource方法
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断beanFactory当中是否有messageSource,如果没有就去构建一个
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
initApplicationEventMulticaster方法
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断我们的beanFactory当中是否有广播器的实现(applicationEventMulticaster),如果没有就去创建一个,放到我们的beanFatory当中
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
onRefresh方法
// 在AbstractApplicationContext当中是一个空实现,是通过我们子类去实现
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
// 在web环境中(ServletWebServerApplicationContext)构建一个web容器
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
registerListeners方法
protected void registerListeners() {
// Register statically specified listeners first.
// 向广播器中添加我们监听器的实现
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
// 当earlyEventsToProcess 不为空的时候就会通过我们广播器去发送我们的广播事件,当我们监听机制还没有初始化完毕的时候,容器就去调用我们的广播器发布事件时,就会将我们的事件保存到earlyApplicationEvents 集合当中,当我们监听机制初始化完毕之后就会将这些尚未处理完的事件依次广播出去
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
// publishEvent方法
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
// Multicast right now if possible - or lazily once the multicaster is initialized
// 当earlyApplicationEvents 不为空的时候就会向其中添加对应的事件,当我峨嵋你调用了registerListeners方法之后会将earlyApplicationEvents集合置为null,就不会将事件添加到earlyApplicationEvents 当中
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// Publish event via parent context as well...
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
}
finishBeanFactoryInitializationfan
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 判断beanFactory当中是否含有conversionService以及beanFactory当中有ConversionService的实现,就会向beanFactory当中设置该属性
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
// 如果beanFactory当中没有EmbeddedValueResolver就会给它设置一个
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 获得beanFactory当中的所有LoadTimeWeaverAware实现(通常是AOP织入的工具,不常使用)
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
// 将beanFactory设置为null表示
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 标记我当前正在实例化,在Spring实例化当中不要向beanFactory当中添加新的bean的注册,也会记录下那些beanDefinitionNames正在实例化
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 单例Bean的实例化
beanFactory.preInstantiateSingletons();
}
// freezeConfiguration方法
public void freezeConfiguration() {
// 标记我当前正在实例化
this.configurationFrozen = true;
// 记录下那些beanDefinitionNames正在实例化
this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}
// preInstantiateSingletons方法
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
// 获取beanFactory当中的所有beanDefinition的名称
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 依次对上述获取的beanDefinition的名称进行遍历
for (String beanName : beanNames) {
// 获取对应的RootBeanDefinition类(描述Bean的作用),其主要是描述一个类的源信息,他的作用范围是单例的还是原型的,是否是延迟加载等等
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 之后就判断该类是否不是抽象的,是否是单例的,是否不是延迟加载的,符合这些,才会进行单例化
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 判断其是否是工厂类
if (isFactoryBean(beanName)) {
// 如果是工厂类的话就会在beanName之前加上一个工厂的bean符号标志“&”然后再去调用getBean方法
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
// 如果不是判断其是否是工厂类就调用getBean实例化该Bean
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
// RootBeanDefinition类(部分代码)
public class RootBeanDefinition extends AbstractBeanDefinition {
@Nullable
private BeanDefinitionHolder decoratedDefinition;
@Nullable
private AnnotatedElement qualifiedElement;
boolean allowCaching = true;
boolean isFactoryMethodUnique = false;
@Nullable
volatile ResolvableType targetType;
/** Package-visible field for caching the determined Class of a given bean definition. */
@Nullable
volatile Class<?> resolvedTargetType;
/** Package-visible field for caching the return type of a generically typed factory method. */
@Nullable
volatile ResolvableType factoryMethodReturnType;
/** Package-visible field for caching a unique factory method candidate for introspection. */
@Nullable
volatile Method factoryMethodToIntrospect;
/** Common lock for the four constructor fields below. */
final Object constructorArgumentLock = new Object();
/** Package-visible field for caching the resolved constructor or factory method. */
@Nullable
Executable resolvedConstructorOrFactoryMethod;
/** Package-visible field that marks the constructor arguments as resolved. */
boolean constructorArgumentsResolved = false;
/** Package-visible field for caching fully resolved constructor arguments. */
@Nullable
Object[] resolvedConstructorArguments;
/** Package-visible field for caching partly prepared constructor arguments. */
@Nullable
Object[] preparedConstructorArguments;
/** Common lock for the two post-processing fields below. */
final Object postProcessingLock = new Object();
/** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied. */
boolean postProcessed = false;
/** Package-visible field that indicates a before-instantiation post-processor having kicked in. */
@Nullable
volatile Boolean beforeInstantiationResolved;
@Nullable
private Set<Member> externallyManagedConfigMembers;
@Nullable
private Set<String> externallyManagedInitMethods;
@Nullable
private Set<String> externallyManagedDestroyMethods;
}
// isFactoryBean方法
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
// 实例化这个bean
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
// 查看其有没有实现FactoryBean接口
return (beanInstance instanceof FactoryBean);
}
// No singleton instance found -> check bean definition.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
// No bean definition found in this factory -> delegate to parent.
return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
}
return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}
// getBean方法
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
// doGetBean方法
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 判断是否是工厂类,是否是别名
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 做一个检查是否可以通过缓存获取
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 会优先获取该bean的父类,判断父类的bean是否已经加载过实例化bean了,子类就不必再实例化了
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
// 标记该beanName正在实例化当中
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
// 获取其对应的BeanDefinition对象
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 检查,判断该类是否是抽象类
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 获取该类的DependsOn对象(及获取该类依赖的其他对象)
String[] dependsOn = mbd.getDependsOn();
// 如果dependsOn不为null的化就证明他依赖了其他的对象,我们需要先将其他对象进行实例化,调用getBean方法(通过@DependOn注解可以进行依赖)
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
// 判断该bean是否是单例的如果是的话就调用getSingleton方法
if (mbd.isSingleton()) {
// getSingleton方法中的匿名方法实现了ObjectFactory接口(其中定义了唯一的方法getObject,需要我们通过实现类去实现)
sharedInstance = getSingleton(beanName, () -> {
try {
// getSingleton该方法中调用了ObjectFactory的匿名方法就会跳转到这里,
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
// transformedBeanName方法
protected String transformedBeanName(String name) {
// 使用transformedBeanName方法判断name是否是工厂类,之后调用canonicalName方法判断是否是别名
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
// transformedBeanName方法
public static String transformedBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
// 如果这个bean不是以工厂bean符号做前缀的,就直接返回一个bean name
if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
return name;
}
// 否则就将工厂前缀夫去掉之后再返回bean name
return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
do {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
return beanName;
});
}
// canonicalName方法(判断当前bean的名称是否是一个别名)
public String canonicalName(String name) {
String canonicalName = name;
// 获取别名执行的类的真正名称返回
String resolvedName;
do {
resolvedName = (String)this.aliasMap.get(canonicalName);
if (resolvedName != null) {
canonicalName = resolvedName;
}
} while(resolvedName != null);
return canonicalName;
}
// getSingleton方法
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 判断singletonObjects集合当中是否存在该beanName(将实例化的bean会放入该集合当中,防止重复获取)
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
// isPrototypeCurrentlyInCreation方法
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
// 是否可以通过缓存获取
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
// markBeanAsCreated方法
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
// 将beanName加入到alreadyCreated集合当中
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 从singletonObjects集合中获取对应的bean
Object singletonObject = this.singletonObjects.get(beanName);
// 如果获取到了该bean就证明已经完成实例化,没有获取到就证明未完成,就往下执行
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 做检查(具体什么检查后续百度)
beforeSingletonCreation(beanName);
boolean newSingleton = false;
// 判断刚才的检查是否出现错误,如果存在错误就抛出
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 这里会会跳转回doGetBean方法的匿名方法中
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
// createBean方法
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// 获取bean的class对象
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
// 调用prepareMethodOverrides方法是否有lookup方法
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 调用该方法实例化bean,如果有参数就直接返回bean,如果没有就往下执行(一般手动实现,即我们实现接口重写方法)
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
// resolveBeforeInstantiation方法
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
// 当bean不为null的时候就调用applyBeanPostProcessorsAfterInitialization方法
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
// applyBeanPostProcessorsBeforeInstantiation方法
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
// 获取所有的BeanPostProcessor的实现
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果我们的BeanPostProcessor也实现了InstantiationAwareBeanPostProcessor接口,就会调用该接口的postProcessBeforeInstantiation方法如果返回的result不为null的话,就会将result返回
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 实例化bean(我们可以重写postProcessBeforeInstantiation方法,在其中将对应的类进行实例化)
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
// applyBeanPostProcessorsAfterInitialization方法
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 遍历BeanPostProcessor,并且调用他们的postProcessAfterInitialization方法,给bean添加属性(重写该方法给对应的bean添加属性)
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
// doCreateBean方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
// 判断当前Bean是否是单例的,如果是的话会从factoryBeanInstanceCache中移除
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 由于其还未实例化会进入createBeanInstance方法
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
// createBeanInstance方法
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 获取对应的bean class
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
// 确认是否存在InstanceSupplier(判断其是否是从其他的配置类中加载的)
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 判断当前FactoryMethod是否为空
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
// 返回一个实例化对象
return instantiateBean(beanName, mbd);
}
// determineConstructorsFromBeanPostProcessors方法
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
// 获取BeanPostProcessors实现并判断是否有SmartInstantiationAwareBeanPostProcessor的实现
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
// instantiateBean方法
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
// 获取实例化策略,默认是使用cglib来进行实例化,调用它的instantiate方法,返回一个实例化的bean
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
// 返回的实力类通过BeanWrapper这个类做一个包装
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
// 对BeanWrapper做一个初始化
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
// cglib
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
// getInstantiationStrategy方法,
protected InstantiationStrategy getInstantiationStrategy() {
return this.instantiationStrategy;
}
// instantiate方法
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
// 获取bean对应的构造器
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 通过下面工具类的instantiateClass方法通过反射来实例化(具体实现后续重新整理在查看)
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
// initBeanWrapper方法
protected void initBeanWrapper(BeanWrapper bw) {
// 设置转换方法
bw.setConversionService(getConversionService());
// 设置一些自定义编辑器
registerCustomEditors(bw);
}
finishRefreshf方法
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 情况缓存
clearResourceCaches();
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
resetCommonCaches方法
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
总结
1.prepareRefresh
①容器状态设置
②初始化属性设置
③检查必备属性是否存在
2.obtainFreshBeanFactory
①设置beanFactory序列化ID
②获取beanFactory
3.prepareBeanFactory
①设置BeanFactory一些属性
②添加后置处理器
③设置忽略的自动装配接口
④注册一些组件
4.postProcessBeanFactory
①子类重写以在BeanFactory完成创建后做进一步设置
5.invokeBeanFactoryPostProcessors
①调用BeanDefinitionRegistryPostProcessor实现向容器内添加bean定义
②调用BeanFactoryPostProcessor实现向容器内bean的定义添加属性
6.registerBeanPostProcessors
①找到BeanPostProcessor的实现
②排序后注册进容器
7.initMessageSource
①初始化国际化相关的属性
8.initApplicationEventMulticaster
①初始化事件广播器
9.onRefresh
①创建web容器
10.registerListeners
①添加容器内事件监听器至事件广播器当中
②派发早期事件
11.finishBeanFactoryInitialization
①初始化所有剩下的单实例bean
12.finishRefresh
①初始化生命周期处理器
②调用生命周期处理器onRfresh方法
③发布ContextRefreshEvent事件
④JMX相关处理
13.resetCommonCaches
①清空上述方法产生的数据缓存
BeanDefinition介绍
1.一个对象在Spring中描述,RootBeanDefinition是其常见实现
2.通过操作BeanDefinition来完成bean实例化和属性注入
图-1
图-2
二、Spring框架启动流程
三、面试重点
1.介绍下IOC思想
2.SpringBoot中bean有哪几种配置方式分别介绍下
3.bean的配置你喜欢哪种方式
4.介绍下refresh方法流程
5.请介绍一个refresh中你比较熟悉的方法说出你的作用
6.介绍下bean实例化流程