Spring Source code parsing, spring source code

Source: Internet
Author: User

Spring Source code parsing, spring source code

Let's first look at the class diagram:

In addition to the BeanFactory interface, AbstractBeanFactory mainly implements the AliasRegistry and SingletonBeanRegistry interfaces.

Three functions are provided: alias management, single instance creation and registration, and factory method FactoryBean support.

 

Let's take a look at the main responsibilities of these interfaces and classes:

BeanFactory Spring IOC container Root Interface

-- HierachicalBeanFactory implements container inheritance, that is, it can have a parent BeanFactory

-- ConfigureabelBeanFactory provides the factory configuration function

AliasRegistry defines bean name alias Management

-- SimpleAliasRegistry adds a canonicalName lookup class named api Based on the alias management interface.

SingletonBeanRegistry provides Singleton registration and query services.

-- DefaultSingletonBeanRegistry implements lifecycle management for singleton and DisposableBean (creation, maintenance, and destruction)

-- FactoryBeanRegistrySupport

-- AbstractBeanFactory BeanFactory abstract implementation.

 

In other words, there are several responsibilities:

A. category name management

B. lifecycle management of a single instance

C. FactoryBean corresponding to the factory method initialization class

D, BeanFactory container

 

BeanFactory container responsibilities (BeanFactory, HierachicalBeanFactory, ConfigureableBeanFactory) have been analyzed in the previous article <Spring source code parsing-BeanFactory interface system explanation>. If you are interested, please refer to it.

Today, we mainly analyze the other three responsibilities, the following interfaces and classes (Directory by the way):

1. AliasRegistry defines bean name alias Management

2. SimpleAliasRegistry implements the alias Management Interface

3. SingletonBeanRegistry provides single-instance registration and query services.

4. DefaultSingletonBeanRegistry implements lifecycle management for singleton and DisposableBean (creation, maintenance, and destruction)

5. Support for FactoryBeanRegistrySupport for creating FactoryBean classes by adding factory methods

 

 

1. AliasRegistry defines bean name alias Management

Provides alias registration, search, deletion, and definition determination.

You just need to look at a class chart and do not need to expand it.

 

 

2. SimpleAliasRegistry implements the alias Management Interface

In addition to implementing the api definition, two public APIs are added:

Batch verify the public void resolveAliases (StringValueResolver valueResolver) and the original class name public String canonicalName (String name) corresponding to the search alias)

 

The data is cached with the alias as the key.

1     /** Map from alias to canonical name */2     private final Map<String, String> aliasMap = new ConcurrentHashMap<String, String>(16);

 

Analyze the api implementation logic:

2.1 register registerAlias (String name, String alias) with an alias)

2.2 Delete the alias public void removeAlias (String alias)

If the alias does not exist, throw new IllegalStateException ("No alias '" + alias + "'registered") is returned ");

 

2.3 determine whether an alias exists

Use ConcurrentHashMap's containsKey directly

2.4 get the alias public String [] getAliases (String name)

The main logic is to add a lock, and then call retrieveAliases recursively to find multi-level aliases (that is, to find aliases)

2.5 use StringValueResolver to parse the class name and alias, and then perform cyclic dependency Verification

The StringValueResolver interface is used here. injection is required for specific implementation.

 

 

3. SingletonBeanRegistry provides single-instance registration and query services.

The Singleton registration defined here is a bit tricky, mainly because it is a little low compared with BeanFactory's api, and there is no additional processing.

No matter whether afterPropertiesSet initialization callback is injected during registration.

During the search, no matter whether the Singleton is not initialized or the alias is concerned, no matter how FactoryBean identifies the instance for obtaining FactoryBean itself or getObject initialization.

 

Let's analyze each api.

3.1 register the void registerSingleton (String beanName, Object singletonObject );

The implementation here will no longer call the initialization callback function, such as the afterPropertiesSet of InitializingBean. Therefore, the initialization instance should be received here.

Similarly, the destroy callback will not be called, such as destroy of DisposableBean.

This is obviously different from the registration Singleton in the standard BeanFactory, because various callbacks will be called over there.

 

3.2 find the singleton (String beanName) of a singleton Object );

String [] getSingletonNames ();

Int getSingletonCount ();

Designed for accessing the manual registration Singleton.

Only the initialized singleton and bean definition but not instantiated are found here.

In this case, FactoryBean is not processed (that is, the difference between getObject and factoryBean itself is obtained, &). aliases must be converted in advance for query.

 

3.3 determine whether to protect the singleton boolean containsSingleton (String beanName );

True is returned only when the Singleton has been instantiated. For the rest, check the description of the singleton in 3.2.

 

 

4. DefaultSingletonBeanRegistry implements lifecycle management for singleton and DisposableBean (creation, maintenance, and destruction)

Add the sharing of SingletonBeanRegistry Based on SingletonBeanRegistry registration.

You can also destroy the DisposableBean instance when the container is disabled.

 

4.1 during registration, the following four variables are used for maintenance:

Map <String, Object> singletonObjects cache single-instance with bean name as key

Map <String, ObjectFactory> singletonFactories caches ObjectFactory whose key is bean name.

Map <String, Object> earlySingletonObjects is used to solve the circular dependency of a single instance. The cache preinitialization Singleton with bean name as key.

Set <String> registeredSingletons has registered the name of the singleton bean.

Here, singletonObjects and registeredSingletons data should be synchronized, but they are only applicable to different scenarios. However, they are mutually exclusive with singletonFactories and earlySingletonObjects, that is, they are included in singletonObjects.

  

At the same time, there are also the concepts of inCreationCheckExclusions and singletonsCurrentlyInCreation for Lock control.

SingletonsCurrentlyInCreation the cache bean is being initialized, so that initialization cannot be initiated;

InCreationCheckExclusions directly caches beans that cannot be loaded currently

This part is clear from an example. Before initialization, use beforeSingletonCreation to determine

Here, the inCreationCheckExclusions will judge singletonsCurrentlyInCreation only when it does not contain beanName.

1     protected void beforeSingletonCreation(String beanName) {2         if (!this.inCreationCheckExclusions.containsKey(beanName) &&3                 this.singletonsCurrentlyInCreation.put(beanName, Boolean.TRUE) != null) {4             throw new BeanCurrentlyInCreationException(beanName);5         }6     }

 

4.2 bean dependency management

Use the following three attributes for management:

Map <String, Set <String> containedBeanMap depends on the bean name as the key, which is the dependent class-> Find the dependent class

Map <String, Set <String> dependentBeanMap depends on the original bean name as key

Map <String, Set <String> dependenciesForBeanMap: the dependent bean name is key.

 

4.3 bean destruction

This is similar to initialization. It is easier to view the code on your own.

 

 

5. Support for FactoryBeanRegistrySupport for creating FactoryBean classes by adding factory methods

To add support for FactoryBean, you can use the factory method to initialize the class.

Three new concepts are involved: FactoryBean, BeanPostProcessor, and AccessController. The source code is analyzed.

 

5.1 FactoryBean provides a simple factory method through the T getObject () api. It can be used to create a single instance and a prototype instance. It is mainly used for complex creation process and inconvenient xml configuration.

In fact, this is to use the spring interface to standardize the simple factory design mode, so that you can configure and use it in spring.

For details, see <Spring bean configuration method (Factory method and Factorybean)>

 

5.2 BeanPostProcessor is used to enhance the bean initialization function, similar to the filter in web development.

There are two APIs:

PostProcessBeforeInitialization is called before class initialization, Which is earlier than executing the custom init-method in the setPropertiesSet and xml files of InitializaingBean.

The postProcessAfterInitialization class is called after the initialization. It is executed after the setPropertiesSet of InitializaingBean and the custom init-method in the xml file.

 

5.3 The Security Control of AccessController jdk is not closely related to spring. I suggest you try again later.

In Java, the execution program is divided into two types: local and remote. Local Code is considered trustworthy by default, while remote code is considered untrusted. For trusted local code, you can access all local resources.

In application development, there are some complex security usage. The most common API is doPrivileged. The doPrivileged method gives a piece of trusted code more permissions, even more than the applications that call it, so that you can temporarily access more resources.

So there is a typical spring code.

 1 if (System.getSecurityManager() != null) { 2     AccessControlContext acc = getAccessControlContext(); 3     try { 4         object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { 5             public Object run() throws Exception { 6                     return factory.getObject(); 7                 } 8             }, acc); 9     }10     catch (PrivilegedActionException pae) {11         throw pae.getException();12     }13 }else {14     object = factory.getObject();15 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.