Three ways to create objects:
1, the default constructor is used to create
2, the use of static factory method
1. Write a static factory method class
public class Helloworldfactory {
public static HelloWorld getinstance () {
return new HelloWorld ();
}
}
2. Declare in spring configuration file
<bean id= "HelloWorld2" class= "Com.itheima05.spring.bean.HelloWorldFactory"
Factory-method= "GetInstance" ></bean>
Tells the spring container to take advantage of the Getinsatance static method in the Helloworldfactory class to produce the object
But the process of creating a specific object is done by a programmer.
3. Example Factory method
1. Write an example factory class
public class Helloworldfactory {
Public HelloWorld getinstance () {
return new HelloWorld ();
}
}
2. In the spring configuration file
1, <bean id= "helloWorld3" class= "Com.itheima05.spring.bean.HelloWorldFactory2" ></bean>
Spring container creates objects for HelloWorldFactory2
2, <bean id= "helloworldfactory" factory-bean= "helloWorld3" factory-method= "getinstance" ></bean>
Tells the spring container to invoke the GetInstance method with the HelloWorld3 object
Time to create an object
1, in the default case, the spring container when the start of the creation of the object
In the spring configuration file, the spring container creates an object as long as it is configured in one of the three ways above
Benefit: When the Spring container and the Web container are consolidated, the spring container can be initialized when the Web container is started, if
If there is an error inside the spring container, you will be immediately
If a large amount of data is stored in the bean, and the initialization of the data occurs when the object is created, the data will reside prematurely in memory at this time.
2. If there is lazy-init= "true" in the configuration of a bean in the spring configuration file, the bean creates the object when the Getbean method is called
Not good: You can't find mistakes too early.
Benefit: Load data as needed (when to load)
Three ways that spring creates objects and when they are created