2. Three Methods for Spring IoC to instantiate bean, 2. springiocbean
1. Constructor
That is, in the example mentioned in the previous article, the default no-argument constructor is called.
2. Static factory Method
1) create a class for the method to be executed
public class HelloWorld {public HelloWorld(){System.out.println("aaaa");}public void hello(){System.out.println("hello world");}}
2) create a static Factory
public class HelloWorldFactory {public static HelloWorld getInstance(){return new HelloWorld();}}
3) Compile the applicationContext. xml configuration file.
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <! -- In this configuration, the spring container uses the default constructor to create an object for HelloWorld --> <bean id = "helloWorld" class = "HelloWorld"> </bean> <! -- Use the static factory method to create an object factory-method as the factory method --> <bean id = "helloWorld2" class = "HelloWorldFactory" factory-method = "getInstance"> </bean> </beans>
4) Start the container, create an object, and call the method.
@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");HelloWorld world = (HelloWorld)context.getBean("helloWorld2");world.hello();}
3. instance factory method (omitted)