Spring Source Code-Start 2

Source: Internet
Author: User

Spring Source Code-Start 2

1. The Container starts and triggers the ServletContextEvent event. Create a WebApplicationContext and prepare the configuration.
2. protected void configureAndRefreshWebApplicationContext (ableablewebapplicationcontext wac, ServletContext SC)

A) Make Some uninformed preparations.
B) Set String [] configLocations to web in AbstractRefreshableConfigApplicationContext. the parameters configured in xml (usually spring DAO configuration) look like this: [classpath: spring/dao. xml, classpath: spring/service. -xml, classpath: spring/service-ref.xml, classpath: spring/registry. xml]
C) customizeContext (SC, wac); this method is almost useless as with the above methods. After all, I did not find any configuration parameters ( Not found. Few people configure these items by default)
D) the most important step is the essence of configureAndRefreshWebApplicationContext: void refresh () throws BeansException, IllegalStateException;
I. prepareRefresh (); not introduced
Ii. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory ();
1. This is the main step for loading the Spring core configuration file. It has several small steps.
2. refreshBeanFactory ();
A) Check whether BeanFactory exists. If BeanFactory exists, destroy beans and clear them.
B) createBeanFactory
C) BeanFactorycustomizeBeanFactory (beanFactory); (project name)
D) customizeBeanFactory (beanFactory );
E) loadBeanDefinitions (beanFactory );
I. Not clear
Ii. loadBeanDefinitions (String location, Set ActualResources) Load spring configurations one by One (dao. Data Source, bean, etc)
F) Here, the configuration files are placed in beanFactory.
3. All the above work is to find the configuration files and place them in beanFactory. After all, the subsequent work is executed around this beanFactory.
4. in the following prepareBeanFactory (effecablelistablebeanfactory beanFactory), you must verify beanFactory configurations such as 'loadtimeweaver ', 'loadtimeweaver', and 'systemenvironment, but I didn't see them in various configuration documents. I don't know if it is configured in spring.
Iii. invokeBeanFactoryPostProcessors (ConfigurableListableBeanFactory beanFactory) and registerBeanPostProcessors (beanFactory); here, we start to process various bean configurations, such as org. springframework. context. annotation. internalConfigurationAnnotationProcessor and org. mybatis. spring. mapper. mapperScannerConfigurer and load other configuration files, such as database configuration files.
Iiii. various configurations
// Register bean processors that intercept bean creation.
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 );
In these steps, the configurations in Spring are loaded in detail. Including reading data sources, initializing beans, obtaining beanFactory, initializing sqlSession, querying and loading various annotations (dao, controller, etc)

Paste some source code:

 

 

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));}// 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.beanFactory.preInstantiateSingletons();}

Below is this:
beanFactory.freezeConfiguration();

 

 

public void freezeConfiguration() {this.configurationFrozen = true;synchronized (this.beanDefinitionMap) {this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);}}
Here is
frozenBeanDefinitionNames
Content

 

All the configurations and annotations (@ controller @ service, etc.) are written in beanFactory. That is, Spring treats all components as beans for processing.

This is the implementation and essence of spring ioc.

Source: http://blog.csdn.net/shi1122/article/details/6735423. I have made a detailed introduction to IOC. Worth reading

 

Below is

// Instantiate all remaining (non-lazy-init) singletons.
BeanFactory. preInstantiateSingletons ();

 

public void preInstantiateSingletons() throws BeansException {if (this.logger.isInfoEnabled()) {this.logger.info(Pre-instantiating singletons in  + this);}List
 
   beanNames;synchronized (this.beanDefinitionMap) {// 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.beanNames = new ArrayList
  
   (this.beanDefinitionNames);}for (String beanName : beanNames) {RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);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
   
    () {public Boolean run() {return ((SmartFactoryBean
    ) factory).isEagerInit();}}, getAccessControlContext());}else {isEagerInit = (factory instanceof SmartFactoryBean &&((SmartFactoryBean
    ) factory).isEagerInit());}if (isEagerInit) {getBean(beanName);}}else {getBean(beanName);}}}}
   
  
 

Look at the name. It's no problem.

 

Then

 

for (String beanName : beanNames) {
Come one by one

 

 

public class RootBeanDefinition extends AbstractBeanDefinition
This class defines bean. All others inherit it

 

This article is a good introduction.

The BD here must not be an abstract class. It must be a singleton and cannot be a Lazy (@ Lazy annotation is used for Lazy loading ). Otherwise ~~~~~~~~~~~~~~~~~~~~~ It's just not processing it.

Let's make a judgment to see if it is factoryBean. If not, we will get this Bean:

Source code: (Note that factorybean, for example, sqlSessionFactory)

 

@SuppressWarnings(unchecked)protected 
 
   T doGetBean(final String name, final Class
  
    requiredType, 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.isDebugEnabled()) {if (isSingletonCurrentlyInCreation(beanName)) {logger.debug(Returning eagerly cached instance of singleton bean ' + beanName +' that is not fully initialized yet - a consequence of a circular reference);}else {logger.debug(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 (args != null) {// Delegation to parent with explicit args.return (T) parentBeanFactory.getBean(nameToLookup, args);}else {// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}}if (!typeCheckOnly) {markBeanAsCreated(beanName);}final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.String[] dependsOn = mbd.getDependsOn();if (dependsOn != null) {for (String dependsOnBean : dependsOn) {getBean(dependsOnBean);registerDependentBean(dependsOnBean, beanName);}}// Create bean instance.if (mbd.isSingleton()) {sharedInstance = getSingleton(beanName, new ObjectFactory
   () {public Object getObject() throws BeansException {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 ' + scopeName + ');}try {Object scopedInstance = scope.get(beanName, new ObjectFactory() {public Object getObject() throws BeansException {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);}}}// Check if required type matches the type of the actual bean instance.if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {try {return getTypeConverter().convertIfNecessary(bean, requiredType);}catch (TypeMismatchException ex) {if (logger.isDebugEnabled()) {logger.debug(Failed to convert bean ' + name + ' to required type [ +ClassUtils.getQualifiedName(requiredType) + ], ex);}throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return (T) bean;}
  
 

 

A rough explanation:

Obtain a single example by name (of course, the name must be processed)

protected Object getSingleton(String beanName, boolean allowEarlyReference) {Object singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null) {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 != NULL_OBJECT ? singletonObject : null);}
 

 

 

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.