(Spring-5th) Internal Working Mechanism of spring containers from loading configuration files to instantiating bean, spring-bean
As mentioned above, the lifecycle of spring is as follows: instantiation Prelude --> instantiation --> post-instantiation --> pre-initialization --> post-initialization --> specific bean call --> pre-destruction --> destruction. So what is the internal mechanism from assembling XML attributes to instantiating beans? Let's look at it all.
It is still an old style, with a specific example preemptible. The following is a simple spring framework. (XML, yes. Bean, yes. Spring container. Main function. Although the sparrow is small, it is enough .)
This is XML, easy to understand, and brittle:
1 ...... 2 3 <bean id = "car" class = "com. mesopotamia. test1.Car "4 p: brand =" BMW X5 "5 p: maxSpeed =" 200 "/> 6 </beans>
This is Bean. You must have a child, and you must have a West Weng:
Code 001
1 public class Car {2 private String name; 3 private String brand; 4 private double maxSpeed; 5 public double getMaxSpeed () {6 return maxSpeed; 7} 8 public void setMaxSpeed (double maxSpeed) {9 this. maxSpeed = maxSpeed; 10} 11 12 13 private Log = LogFactory. getLog (Car. class); 14 15 public Car () {16 name = "BMW"; 17 log.info ("calls the Car constructor and instantiates the Car, set the Car name attribute to "+ name); 18} 19 public String getName () {20 return name; 21} 22 public void setName (String name) {23 this. name = name; 24} 25 public String getBrand () {26 return brand; 27} 28 public void setBrand (String brand) {29 this. brand = brand; 30} 31 32 33 public String toString () {34 return "name" + name + "model" + "Speed:" + maxSpeed; 35} 36 37 38}
The following is the startup function! Competent:
Code 002
1 public class Main {2 private static Log log = LogFactory. getLog (Main. class); 3 4 public static void main (String args []) {5 ApplicationContext ctx = new ClassPathXmlApplicationContext ("com/mesopotamia/test1 /*. xml "); 6 Car car1 = ctx. getBean ("car", Car. class); 7 log.info (car1.toString (); 8}
But I want to focus on the logs after the main function is run:
Code 003
1 20:19:04, 318 INFO [main] (AbstractApplicationContext. java: 456)-Refreshing org. springframework. context. support. classPathXmlApplicationContext @ 1ff5ea7: startup date [Mon Nov 16 20:19:04 CST 2015]; root of context hierarchy2 20:19:04, 371 INFO [main] (XmlBeanDefinitionReader. java: 315)-Loading XML bean definitions from file [C: \ MySoftware \ workspace \ springtest \ WebRoot \ WEB-INF \ classes \ com \ mesopotamia \ test1 \ beans. xml] 3 20:19:04, 482 INFO [main] (DefaultListableBeanFactory. java: 555)-Pre-instantiating singletons in org. springframework. beans. factory. support. defaultListableBeanFactory @ 6e293a: defining beans [car]; root of factory hierarchy4 20:19:04, 483 INFO [main] (Car. java: 22)-the Car constructor is called, the Car is instantiated, and the Car name attribute is set to: BMW 5 20:19:04, 533 INFO [main] (Main. java: 15)-Name: BMW model speed: 200.0
At the beginning, the method in AbstractApplicationContext was loaded. So what did this method do? In fact, the first line is printed by the refresh () method of AbstractApplicationContext. The method is loaded when the container is started. Let's unveil the refresh.
First, this AbstractApplicationContext must be the parent class of ClassPathXmlApplicationContext. Otherwise, how can I run the 5th line of code 002 to the methods in AbstractApplicationContext? The child is beaten. Of course, it's called Dad.
In MyEclipse, press ctrl and click "ClassPathXmlApplicationContext". Then you will find the inheritance relationship (for example, use "->" to indicate that the subclass points to the inherited parent class ):
ClassPathXmlApplicationContext-> AbstractXmlApplicationContext-> AbstractRefreshableConfigApplicationContext-> AbstractRefreshableApplicationContext-> AbstractApplicationContext.
We enter AbstractApplicationContext to see the true nature of the refresh () method:
1 public void refresh() throws BeansException, IllegalStateException { 2 synchronized (this.startupShutdownMonitor) { 3 // Prepare this context for refreshing. 4 prepareRefresh(); 5 6 // Tell the subclass to refresh the internal bean factory. 7 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 8 9 // Prepare the bean factory for use in this context.10 prepareBeanFactory(beanFactory);11 12 try {13 // Allows post-processing of the bean factory in context subclasses.14 postProcessBeanFactory(beanFactory);15 16 // Invoke factory processors registered as beans in the context.17 invokeBeanFactoryPostProcessors(beanFactory);18 19 // Register bean processors that intercept bean creation.20 registerBeanPostProcessors(beanFactory);21 22 // Initialize message source for this context.23 initMessageSource();24 25 // Initialize event multicaster for this context.26 initApplicationEventMulticaster();27 28 // Initialize other special beans in specific context subclasses.29 onRefresh();30 31 // Check for listener beans and register them.32 registerListeners();33 34 // Instantiate all remaining (non-lazy-init) singletons.35 finishBeanFactoryInitialization(beanFactory);36 37 // Last step: publish corresponding event.38 finishRefresh();39 }40 41 catch (BeansException ex) {42 // Destroy already created singletons to avoid dangling resources.43 destroyBeans();44 45 // Reset 'active' flag.46 cancelRefresh(ex);47 48 // Propagate exception to caller.49 throw ex;50 }51 }52 }
If you only see the first sight in your life, are you stunned to see such a beautiful code? OK, I know that you are not good at English. I will give you a rough idea about what you have done in refresh (). These steps are actually a series of beautiful actions before instantiation:
Row 3: Prepare bean factory (BeanFactory is the infrastructure of spring framework)
Row 16th: Call BeanFactoryPostProcessors (factory post-processor) registered as beans (factory post-processor is responsible for processing beans that have not been formed before instantiation)
Row 3: Register BeanPostProcessors (Bean post-processor) to block bean creation. (This post-processor is needed for further processing of the instantiated bean)
Row 3: Initialize the message source (International Information Resource ). (Is it easy to understand internationalization? For example, you can switch between Chinese and English versions, and we will explain it in detail later)
Row 3: Initialize the application context event broadcaster. (Spring has a complete set of event publishing and listening mechanisms. The event broadcaster is responsible for notifying the listener about the event and implementing the event. Will be explained in detail later ).
Row 3: Initialize other special beans.
Row 31st: Check whether there is a listener and register the listener (the listener is the same as bean and needs to be placed in the registry. Will be explained in detail later ).
Row 34th: Initialize all beans in a single instance (except for beans in the lazy mode). After the bean in a single instance is initialized, the bean reference is placed in the cache of the spring container, the caller uses the same amount of reference. Any modification made by the caller to the bean will affect other callers. The lazy Mode means that the spring container will not be initialized when it is started, but will not be initialized when this bean is used. The lazy-init attribute in the XML <bean> label sets the lazy mode or the diligent mode. false indicates the diligent mode, and true indicates the lazy mode.
Row 3: create a context refresh event and publish the broadcaster. (The event mechanism will be described in detail later)
The above are the details before and after bean instantiation. So what factory post-processor and bean post-processor are called?
The following describes how to create a complete bean job:
The whole is as follows:
Simple:
Read XML, convert it into BeanDefinition, and instantiate BeanDefinition.
Details:
After ResourceLoader loads XML configuration information, BeanDefinitionReader reads the configuration information file and parses each <bean> into a BeanDefinition object and saves it in the registry. The container first scans the Registry to retrieve the factory and then processes the BeanDefinition in the registry. The Spring container then extracts the processed BeanDefinition from the registry and starts bean instantiation. During instantiation, BeanWapper first encapsulates the bean and configures attributes. Finally, we use the Bean post-processor in the Registry to dress up and assemble a ready Bean. (The registry is similar to a Map <K, V>. All the beans, whether business beans or spring beans, are put in the Registry and obtained when used ).
Here's the details:
The voice stops here. Wash and sleep.
Those who know is not confused, those who are benevolent are not worried, and those who are brave are not afraid.
---- Ziyue