Four ways to instantiate beans in spring
preface
Before introducing the instantiation of beans, we first need to introduce what beans are and how beans are configured.
If spring is regarded as a large factory, the bean in the spring container is the product of the factory. If you want to use the spring factory to produce and manage beans, you need to specify which beans you need in the configuration file and how you need to assemble these beans together.
The spring container supports two formats of configuration files, namely, properties file format and XML file format. In actual development, the most commonly used format is XML file format. Therefore, in the following explanation, we will explain the configuration of XML file format. The root element of the XML configuration file is < beans >, which can contain multiple sub elements < bean >, each of which defines a bean and describes how the bean should be assembled into the spring container< The attributes in the bean > element are as follows:
In the configuration file, an ordinary bean only needs to define ID and class attributes. The way to define a bean is as follows:
In the above code, two beans are defined with the ID and name attributes respectively, and the class element is used to specify their corresponding implementation class. If the ID and name are not specified, spring will use the class value as the ID.
Four ways spring instantiates beans
This article mainly introduces four methods of instantiating beans (injection method) or dependent object instantiation. In the above program, what method is used to create bean objects and the constructor is used (spring can create class objects when the constructor is privatized)
There are four common creation methods:
1) Setter method
2) Constructor
3) Static factory
4) Example factory
1、 Using setter mode
2、 Constructor
3、 Static factory mode
4、 Example factory
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.