测试准备
package iocCode;
public class Person {
private int age;
private String name;
public Person(int age, String name) {
System.out.println("创建Person");
this.age = age;
this.name = name;
}
public Person() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person01" class="iocCode.Person" scope="singleton">
<property name="age" value="19"></property>
<property name="name" value="张三"></property>
</bean>
<bean id="person02" class="iocCode.Person" scope="singleton" >
<property name="age" value="20"></property>
<property name="name" value="李四"></property>
</bean>
<bean id="person03" class="iocCode.Person" scope="singleton" lazy-init="true">
<property name="age" value="21"></property>
<property name="name" value="王五"></property>
</bean>
<bean id="person04" class="iocCode.Person" scope="prototype">
<property name="age" value="22"></property>
<property name="name" value="麻子"></property>
</bean>
<bean id="person06" class="iocCode.Person" scope="singleton" depends-on="person01">
<property name="age" value="24"></property>
<property name="name" value="二狗"></property>
</bean>
</beans>
public class Test {
public static void main(String[] args) {
//1 、IOC容器创建
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Person person01 = (Person)applicationContext.getBean("person01");
System.out.println(person01);
}
}
二 、什么时候创建单实例Bean的
上面说明Spring启动的时候,创建IOC容器的时候就给我们创建好了单实例的Bean
那么我们就debug就进入new ClassPathXmlApplicationContext("ApplicationContext.xml")
。看Spring是如何创建单实例的Bean的
创建Bean的源码
1、ClassPathXMLApplicationContext构造器:
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
//进入refresh
refresh();
}
}
2、refresh() (AbstractApplicationContext)
@Override
public void refresh() throws BeansException, IllegalStateException {
//同步锁,保证多线程情况下IOC容器只被创建一次
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//刷新容器
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//Spring解析XML,将要创建的所以Bean的配置信息保存起来
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//准备BeanFactory
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//BeanFactory的后置处理器
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//执行BeanFactory的后置处理器的注册
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//Spring自己的后置处理器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this cont功能
//用来支持国际化功能
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.
//初始化Bean(这是仔细研究的方法)
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();
}
}
}
在ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
;中我们可以看到以下信息,里面包含了XML中我们定义Bean的定义信息,说明此步是用来解析XML的
finishBeanFactoryInitialization(beanFactory)
;是初始化Bean的重点方法
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();
}
beanFactory.preInstantiateSingletons();
是初始化所有非懒加载的单实例Bean
@Override
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.
//拿到所有要创建的bean的名字
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
//按顺序创建Bean
for (String beanName : beanNames) {
//根据Bean的id获取Bean的定义信息
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//判断Bean不是抽象的,是单实例,不是懒加载的
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//是不是是实现了BeanFactory的Bean,我们的Person没有实现,所以下面不执行
if (isFactoryBean(beanName)) {
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) {
//创建BeanI(重点代码)
getBean(beanName);
}
}
}
else {
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();
}
}
}
}
getBean(beanName);
创建Bean,debug进入
可以看到所有的getBean
都调用了doGetBean
,那么doGetBen
就是创建Bean的具体逻辑
doGetBen
是创建Bean的具体逻辑
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.
//先看已经注册的单实例Bean,有没有我们这个Bean,由于是第一次创建,里面没有
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,这里没有
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);
}
}
//标记这个Bean被创建了,线程安全 把这个Bean放入alreadyCreated
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
//获取当前Bean的定义信息
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//拿到创建当前Bean之前需要提前创建的Bean,depends-on 属性
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.
if (mbd.isSingleton()) {//如果当前要创建的bean是单例的,进入getSingleton
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;
}
getSingleton方法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 尝试从singletonObjects中拿bean,singletonObjects是用来缓存已经创建的单实例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 {
//利用反射创建对象
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) {
//把创建的单实例Bean放到singletonObjects中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
最终创建好的对象会保存在一个ConcurrentHashMap中,ConcurrentHashMap是线程安全的,而且get操作是无锁的,性能高
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
IOC容器其实就是一个众多map的集合
总结:
getBean每次也会执行 Object sharedInstance = getSingleton(beanName);先判断是否已经创建了Bean,如果没有再创建Bean
BeanFactory和ApplicationContext的区别
- ApplicationContext是BeanFactory的子接口
- BeanFactory是bean工厂接口,负责创建Bean实例,容器里面保存的所有单实例bean其实是一个map,BeanFactory是Spring最底层的接口
- ApplicationContext:是容器接口,更多的是负责容器功能的实现,(可以基于BeaFactory创建好的对象之上完成强大的容器),容器可以从map获取这个bean,并且AOP和DI
Spring中最大的设计模式就是工厂模式