ioc容器启动创建Bean
ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc2.xml");
Object book = ioc.getBean("book");
System.out.println(book);
1. 进入ClassPathXmlApplicationContext构造器
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
2. 进入refresh()方法
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
//创建ClassPathXmlApplicationContext对象
this.prepareRefresh();
//beanFactory 解析读取xml配置文件,将要创建的所有bean的信息保存起来(还没有创建)
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
/*
BeanFactory的后置处理器
Allows post-processing of the bean factory in context subclasses.
*/
this.postProcessBeanFactory(beanFactory);
//Invoke factory processors registered as beans in the context.
this.invokeBeanFactoryPostProcessors(beanFactory);
//注册后置处理器
this.registerBeanPostProcessors(beanFactory);
//初始化消息源,支持国际化功能
this.initMessageSource();
//初始化事件转换器
this.initApplicationEventMulticaster();
//留给子类的方法
this.onRefresh();
//注册监听器
this.registerListeners();
//初始化所有单实例Bean
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
3.进入AbstractApplicationContext类的 finishBeanFactoryInitialization()
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
//初始化类型转换的组件服务
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.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
//设置临时的类加载器
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
//冻结配置
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
//预初始化所有单实例Bean
beanFactory.preInstantiateSingletons();
}
4. 进入DefaultListableBeanFactory类的preInstantiateSingletons()
创建单实例bean
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
//拿到所有要创建bean的名字
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
//按配置顺序创建Bean
for (String beanName : beanNames) {
//getMergedLocalBeanDefinition:拿到bean的定义信息,
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象的、是单实例的、非懒加载的Bean
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//实现FactoryBean接口的bean
if (isFactoryBean(beanName)) {
...........
}
else {
getBean(beanName);
}
}
}
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();
}
}
}
}
5. getBean()方法
getBean()方法:getBean(beanName)
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
调用doGetBean方法:doGetBean(name, null, null, false)
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);
//从缓存(已经注册的单实例bean)检查有没有这个bean,第一次创建bean是没有的
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.
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);
}
}
if (!typeCheckOnly) {
//标记bean被创建
markBeanAsCreated(beanName);
}
try {
//
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//拿到当前bean所依赖的、需要提前创建的bean
String[] dependsOn = mbd.getDependsOn();
//有,则循环创建
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实例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
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;
}
7.getSingleton()
getSingleton(String beanName, ObjectFactory<?> singletonFactory)
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//将bean从singletonObjects这个ConcurrentHashMap拿出来
//ConcurrentHashMap:按对象的名和实例缓存所有的单实例Bean
//这里第一次创建,是拿不到的
Object singletonObject = this.singletonObjects.get(beanName);
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 {
//将Bean创建出来了
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) {
//把创建好的对象保存在一个map中:DefaultSingletonBeanRegistry-singletonObject这个map中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
-
创建单实例:
singletonObject = singletonFactory.getObject(); -
ioc中保存单实例bean的容器
DefaultSingletonBeanRegistry-singletonObject
8. 总结:
- 第一次创建容器:
ClassPathXmlApplicationContext构造器 refresh() ->
AbstractApplicationContext类
finishBeanFactoryInitialization(beanFactory) ->
DefaultListableBeanFactory类
preInstantiateSingletons() ->
getBean(beanName) ->
AbstractBeanFactory类
doGetBean(name, null, null, false) ->
getSingleton() ->
DefaultSingletonBeanRegistry类
singletonFactory.getObject()创建
addSingleton(beanName, singletonObject)保存到容器
- 使用getBean拿到单实例对象
ioc.getBean(’’ xx’’) ->
AbstractBeanFactory类
getBeanFactory().getBean(name) ->
doGetBean(name, null, null, false) ->
Object sharedInstance = getSingleton(beanName)->
DefaultSingletonBeanRegistry类
getSingleton(beanName, true) ->
Object singletonObject = this.singletonObjects.get(beanName)
9.BeanFactory和ApplicationContext的区别
-
ApplicationContext是BeanFactory的子接口;
-
BeanFactory:bean工厂,负责创建bean实例;
-
ApplicationContext:是容器接口,更多的负责容器功能的实现;(可以基于BeanFactory创建好的对象之上,完成强大的容器功能),
-
容器里保存的所有单例bean,其实是一个map(singletonObject);容器从map中获取这个bean,并且后面的aop、di等功能都是在ApplicationContext接口下面的类实现的。
-
BeanFactory是最底层的接口,ApplicationContext是留给我们使用的容器接口。ApplicationContext是BeanFactory的子接口;
-
Spring里最大的模式就是工厂模式 —帮用户创建Bean