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

时间:2022-05-16
本文章向大家介绍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();
      }
}
<?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">
    <!-- 
        beans  存放了很多个类
            把一个类放入到spring容器中,该类就是bean
     -->
     <!-- 
        一个bean就是描述一个类
          id就是标示符
                命名规范:类的第一个字母变成小写,其他的字母保持不变
          class为类的全名
      -->
     <bean id="helloWorld" class="com.sanmao.spring.ioc.HelloWorld"></bean>
    <!--alias  别名-->
    <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>
    <!--factory-bean  指向实例工厂的bean-->
    <!--factory-bean 实例工厂对象的方法-->
    <bean  id="helloWorld3" factory-bean="helloWorldFactory2" factory-method="getInstance"></bean>

</beans>