Spring since 3.1 it is recommended to use DefaultListableBeanFactory and XmlBeanDefinitionReader these two classes, XmlBeanFactory is DefaultListableBeanFactory subclasses.
The first way to create a Bean factory is simpler
XmlBeanFactory factory = new XMLBeanFactory(new ClassPathResource("Bean.xml"))
Preson p =(Person) factory.getBean(Person.class);
The second creates Bean factories
ClassPathResource resource = new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(resource);
Spring loads resources and assembles objects:
-
Define the Spring configuration file
-
The Spring configuration file is abstracted from the Resurce object as a Resource object
-
Define Bean factories (various BeanFactories)
-
Define the XMLBeanDefinitionReader object and pass in the factory as an argument for subsequent callbacks
-
Read previously abstracted Resource objects (containing parsing of XML files) using the XMLBeanDefinitionReader object
-
In essence, the XML file parsing is by XmlBeanDefinitionReader object to a BeanDefinitionParserDelegate entrusted to complete, in essence is used here to delegate pattern.
-
After the IOC container is created, users can obtain the required object information through the container
Note: In DefaultBeanDefinitionDocumentReader doRegisterBeanDefinitions method using the classic template method in the class of design patterns, a subclass can override preProcessXml and postProcessXml method, Implement custom extensions to XML configuration files.
conclusion
- Spring’s beans are actually cached in the CurrentHashMap object
- Before creating a Bean, you first need to set the Bean’s creation identifier to indicate that the Bean has been or will be created to increase caching efficiency.
- Use the scope attribute of the bean to determine whether the scope is singleton or Prototype, and then create the corresponding bean object.
- Java reflection is used to create instances of beans, checking for access modifiers before creation and, if not public, calling setAccessible to break through Java’s syntaxal limitations so that object instances can be created through private constructors
- Next, find the bean’s property value and complete the property injection
- Add the created Singleton object to the cache for the next call