1.構造器html
也就是在上一篇講的那個例子,調用默認的無參構造函數java
2.靜態工廠方法spring
1)建立須要執行的方法的類app
public class HelloWorld { public HelloWorld(){ System.out.println("aaaa"); } public void hello(){ System.out.println("hello world"); } }
2)建立靜態工廠函數
public class HelloWorldFactory { public static HelloWorld getInstance(){ return new HelloWorld(); } }
3)編寫applicationContext.xml配置文件xml
<?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"> <!-- 在這個配置中,spring容器要用默認的構造函數爲HelloWorld建立對象 --> <bean id="helloWorld" class="HelloWorld"></bean> <!-- 採用靜態工廠方法建立對象 factory-method爲工廠方法 --> <bean id="helloWorld2" class="HelloWorldFactory" factory-method="getInstance"></bean> </beans>
4)啓動容器,建立對象,調用方法htm
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld world = (HelloWorld)context.getBean("helloWorld2"); world.hello(); }
3.實例工廠方法(略)對象