作者:三封酒可_894 | 来源:互联网 | 2024-10-20 20:50
/*** spring容器做的事情:* 解析spring的配置文件,利用Java的反射机制创建对象**/ public class testHelloWorld {@Test public void testHelloWorld (){ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml" );HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorld" );helloWorld.sayHello();HelloWorld alias=(HelloWorld)context.getBean("三毛" );alias.sayHello();}/*** 静态工厂* 在spring 内部,调用了HelloWorldFactory 内部的 getInstance 内部方法* 而该方法的内容,就是创建对象的过程,是由程序员来完成的* 这就是静态工厂* */ @Test public void testHelloWorldFactory (){ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml" );HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorldFactory" );helloWorld.sayHello();}/*** 实例工厂* 1.spring容器(beans)创建了一个实例工厂的bean* 2.该bean 调用了工厂方法的getInstance 方法产生对象* */ @Test public void testHelloWorldFactory2 (){ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml" );HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorld3" );helloWorld.sayHello();} }
public class HelloWorld {public HelloWorld (){System.out .println("spring 在默认的情况下,使用默认的构造函数" );}public void sayHello (){System.out .println("hello" );} }
public class HelloWorldFactory {public static HelloWorld getInstance (){return new HelloWorld();} }
public class HelloWorldFactory2 {public HelloWorld getInstance (){return new HelloWorld();} }
<beans xmlns &#61;"http://www.springframework.org/schema/beans" xmlns:xsi &#61;"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation &#61;"http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd" > <bean id &#61;"helloWorld" class &#61;"com.sanmao.spring.ioc.HelloWorld" > bean ><alias name &#61;"helloWorld" alias &#61;"三毛" > alias ><bean id &#61;"helloWorldFactory" class &#61;"com.sanmao.spring.ioc.HelloWorldFactory" factory-method &#61;"getInstance" > bean ><bean id &#61;"helloWorldFactory2" class &#61;"com.sanmao.spring.ioc.HelloWorldFactory2" > bean ><bean id &#61;"helloWorld3" factory-bean &#61;"helloWorldFactory2" factory-method &#61;"getInstance" > bean >beans >