Spring容器创建对象的三种方式

/**
 * spring容器做的事情:
 *    解析spring的配置文件,利用Java的反射机制创建对象
 *
 */
public class testHelloWorld {
    @Test
    public void testHelloWorld(){
        //启动sping容器
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //从spring容器中把对象提取出来
        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="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">
    
     
     <bean id="helloWorld" class="com.sanmao.spring.ioc.HelloWorld">bean>
    
    <alias name="helloWorld" alias="三毛">alias>
    

    <bean id="helloWorldFactory" class="com.sanmao.spring.ioc.HelloWorldFactory"
                 factory-method="getInstance"
    >bean>

    
    <bean id="helloWorldFactory2" class="com.sanmao.spring.ioc.HelloWorldFactory2">
    bean>
    
    
    <bean  id="helloWorld3" factory-bean="helloWorldFactory2" factory-method="getInstance">bean>

beans>

你可能感兴趣的:(Spring容器创建对象的三种方式)