Detailed explanation of spring instantiation method and code
This article introduces several methods of spring instantiating beans through example code. Let's take a look at the specific content.
1. Use class constructor to realize instantiation (bean's own constructor)
2. Use static factory method to realize instantiation
3. Use the instance factory method to realize instantiation (through beans of other entities)
We usually call the bean factory or ApplicationContext that is responsible for loading beans a spring container. Both load beans through XML configuration files. The main difference between ApplicationContext and beanfactory is that beanfactory delays loading and instantiates the bean to get only when getBean () is called. If an attribute of a bean cannot be injected, an exception will be thrown at this time; By default, ApplicationContext instantiates all beans when initializing itself, unless lazy init = "true" is set for beans, which is helpful to check whether the dependent properties can be injected.
In addition, ApplicationContext provides more extended functions, such as internationalization of resource files to be loaded and beanpostprocessor. Therefore, in J2EE applications, we usually choose to use ApplicationContext. Whether using beanfactory or ApplicationContext, spring initializes beans in a singleton mode by default
For the initialization of beanfactory, the following code is usually used:
For the initialization of ApplicationContext, it is usually on the web Configuration in XML:
summary
The above is all about the detailed code explanation of the way spring instantiates beans in this article. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!