《 In depth understanding of Spring Series 4 :BeanDefinition Prelude to loading 》 I mentioned , For non delayed singletons bean The initialization of is in finishBeanFactoryInitialization(beanFactory) Finish in . Enter this method , The code is as follows .

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.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(new StringValueResolver() {
public String resolveStringValue(String strVal) {
return 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) {
} // 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.

Focus on the last line of code ,beanFactory.preInstantiateSingletons() Complete initialization of all non delayed singletons bean, Enter the specific implementation of this method , The code is as follows .

public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("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.
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // Only right The singleton bean To deal with
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit();
}, getAccessControlContext());
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
if (isEagerInit) {
else {
} // 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(new PrivilegedAction<Object>() {
public Object run() {
return null;
}, getAccessControlContext());
else {

As you can see from the code above , Only for non delayed singletons bean To initialize ,scope For other values bean It will be initialized when it is used , Such as prototype. Focus on getBean Method , This method looks familiar , In fact, that is 《 In depth understanding of Spring One of series : The opening 》 Example code used in getBean,Spring This method has been reused .getBean The concrete implementation of the method is in doGetBean In the method , The code of this method is very long, so we don't paste the code . stay doGetBean in , First, it initializes its dependencies bean, And then initialize itself , This method focuses on the following code snippet .

 // Create bean instance.
if (mbd.isSingleton()) {// The singleton bean initialization
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
try {
// Conduct doCreateBean Method
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.
throw ex;
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) { // Many cases bean initialization
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
prototypeInstance = createBean(beanName, mbd, args);
finally {
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);

Trace code createBean(beanName, mbd, args) Get into doCreateBean In the method , In this way bean Instance creation 、 Property fill 、 take bean Add instance to singleton bean In the cache of the instance .

doCreateBean Method has the following code snippet .

if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);

createBeanInstance In the method bean Instance creation , The specific process can continue to track the code to see , In fact, reflection is used to create instance objects .

In depth understanding of Spring Series six :bean More about initialization

  1. In depth understanding of Spring Series seven :web Apply automatic assembly Spring To configure

    Reprint stay < In depth understanding of Spring One of series : The opening > Use the following method to load Spring ...

  2. In depth understanding of Spring Series 4 :BeanDefinition Prelude to loading

    Reprint ...

  3. In depth understanding of Spring Series five :BeanDefinition load

    Reprint Next chapter < In depth understanding of Spring Series 4 :BeanDefinition Prelude to loading >, Into the ...

  4. In depth understanding of Spring Series three :BeanFactory analysis

    Reprint ...

  5. In depth understanding of Spring The second series :BeanDefinition analysis

    Reprint ...

  6. spring Extension point two :spring About China bean initialization 、 Destruction, etc ,ApplicationContextAware take ApplicationContext Inject

    <spring Extension point two :spring About China bean initialization . Destruction, etc ,ApplicationContextAware take ApplicationContext Inject > <spring ...

  7. In depth understanding of Spring Series eight : Common extension interfaces

    Reprint Spring It not only provides a basic framework for rapid development , It also provides a lot of extensible interfaces , Used to satisfy some amount of ...

  8. Spring Series of bean Use

    One .Bean The definition of <bean id="userDao" class=""/> ...

  9. Spring series ( Two ) Bean assembly

    The act of creating collaborative relationships between application objects is called assembly (wiring), This is also DI The essence of . Spring Middle assembly Bean The way Spring There are three kinds of assemblies available Bean The way . implicit Bean Discovery mechanism and automatic assembly Java ...

Random recommendation

  1. NOSDK-- The implementation of one click packaging ( 3、 ... and )

    1.3  Script introduction of compiling and copying resources This section describes how to compile and copy resources shell Script , namely : tools:                                             // Save the universal work ...

  2. To configure php.ini Realization PHP File upload function

    This article describes how to configure php.ini Realization PHP File upload function . It involves php.ini In the configuration file upload_tmp_dir.upload_max_filesize.post_max_size Options such as , these ...

  3. android Custom control ( Theoretical knowledge learning + Explanation of custom attributes )

    View Trees and UI Interface architecture diagram   UI Interface architecture diagram : android The outermost layer of the view is a window object . phoneWindow To achieve . phoneWindow Will a decorView As the root of the whole layout vie ...

  4. liteUploader The encapsulation of upload control

    // The original binding method $('#' + frm_name).liteUploader({ script: url, params: { type: "image", size: siz ...

  5. translate :SET Variable( Submitted to MariaDB The official manual )

    This paper is about mariadb The official manual :SET Variable Translation of . original text : I submit to MariaDB The translation of the official manual :https:/ ...

  6. Java The basic application of transaction

    Basic introduction Transaction is the basic guarantee of data consistency , That is to say, all operations in a transaction are successful , Or they all failed , Partial success is not allowed . What we often talk about is jdbc Business , Of course Java There are other things in the business , And using jdbc There are a lot of things to pay attention to , ...

  7. MySql 8.0 Version USES navicat There's no way to solve it

    Go through the command line first mysql Of root Account : Change encryption ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE ...

  8. 6. Simple extraction of little red book app Save the data txt-2

    Simply grab the page information : Something to be aware of : auth-sign and auth They all have certain timeliness , also url primary url yes https It's going to be changed to http request . This parameter problem needs to be solved through mitmdump Go get it, please ...

  9. libcurl HTTP POST The request is sent to the server json data 【 turn 】

    Reprint : Reprint : ...

  10. js Several commonly used verifications

    /// <summary> ///1. Use regular expressions to verify Parameters whether Is the value /// </summary> /// <param name="trNumber ...