spring中Bean的实例化方式

  1. 无参数构造
    对于这种方式,注意Bean类中必须提供无参数构造。

创建bean类

package com.itcast.bean;

public class Bean1 {
    public Bean1(){
        System.out.println("bean1的无参构造");
    }
    public void show(){
        System.out.println("bean1 show...");
    }
}

在applicationContext.xml配置文件中添加属性

 <bean id="bean1" class="com.itcast.bean.Bean1">

测试:
三种方式均可获得bean实例
注意:FileSystemXmlApplicationContext相比ClassPathXmlApplicationContext加载配置文件时要添加src路径

public class BeanTest {
    @Test
    public void test1() {
        //使用beanFactory获取bean1实例
        Resource resource = new ClassPathResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        Bean1 bean1 = (Bean1) factory.getBean("bean1");
        bean1.show();
    }
        @Test
    public void Test2() {
     //使用ApplicationContext 获取bean1实例
        ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Bean1 bean1 = (Bean1) ApplicationContext.getBean("bean1");
        bean1.show();
    }

    @Test
    public void test3() {
        ApplicationContext ApplicationContext = new FileSystemXmlApplicationContext("src/applicationContext.xml");
        Bean1 bean1 = (Bean1) ApplicationContext.getBean("bean1");
        bean1.show();
    }
   }
  1. 静态工厂方法
    需要创建一个工厂类,在工厂类中提供一个static返回bean对象的方法就可以。
    创建bean2类
package com.itcast.bean2;

public class Bean2 {
    public void show(){
        System.out.println("hello bean2....");
    }
}

创建bean2Factory类

package com.itcast.bean2;

public class Bean2Factory {
    public static Bean2 createBean2(){
        return new Bean2();
    }
}

在applicationContext.xml配置文件中添加属性

    <bean id="Bean2Factory" class="com.itcast.bean2.Bean2Factory" factory-method="createBean2"></bean>

测试:

    @Test
    public void test4(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Bean2 Bean2 = (Bean2) applicationContext.getBean("Bean2Factory");
        Bean2.show();
    }
  1. 实例工厂方法
    需要创建一个工厂类,在工厂类中提供一个非static的创建bean对象的方法,在配置文件中需要将工厂配置,还需要配置bean
    创建bean3类
package com.itcast.bean3;

public class Bean3 {
    public void show(){
        System.out.println("hello bean3...");
    }
}

创建Bean3Factory类

package com.itcast.bean3;

public class Bean3Factory {
    public Bean3 createBean3(){
        return new Bean3();
    }
}

在applicationContext.xml配置文件中添加属性

    <bean name="Bean3Factory" class="com.itcast.bean3.Bean3Factory"></bean>
    <bean name="Bean3" factory-bean="Bean3Factory" factory-method="createBean3"></bean>

测试:

    @Test
    public void test5(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Bean3 bean3 = (Bean3) applicationContext.getBean("Bean3");
        bean3.show();
    }

猜你喜欢

转载自blog.csdn.net/Marion158/article/details/85269351