Spring bean实例化三种方式

无参构造函数实例化(最常见的方式)

类文件

public class ExampleBean{
    public void print(String val) {
        System.out.println("com.woniu..spring.test.ExampleBean:print ->" + val);
    }
}

bean

<bean id="exampleBean" class="com.woniu.spring.test.ExampleBean"/>

测试类

public void SpringBeansTest() {
        ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");  
        ExampleBean exampleBean= (ExampleBean) beans.getBean("exampleBean");
        exampleBean.print("无参数构造");
}

静态工厂方法实例化

静态工厂类

public class ExampleBeanStaticFactory {
    private static ExampleBean exampleBean = new ExampleBean();
    private ExampleBeanStaticFactory () {}

    public static ExampleBean createExampleBean() {
        return exampleBean;
    }
}

bean

<bean id="createExampleBean" class="com.woniu.spring.test.ExampleBeanStaticFactory" factory-method="createExampleBean"/>

测试方法

public void SpringBeansTest() {
        ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");  
        ExampleBean createExampleBean = (ExampleBean) beans.getBean("createExampleBean");
        createExampleBean.print("静态工厂类实例化");
}

实例工厂方法实例化

实例工厂类
一个工厂类可以包含多个工厂方法

public class ExampleBeanStaticFactory {

    private ExampleBean exampleBean1 = new ExampleBean();

    private ExampleBean exampleBean2 = new ExampleBean();

    public static ExampleBean createExampleBean1() {
        return exampleBean1;
    }

    public static ExampleBean createExampleBean1() {
        return exampleBean2;
    }
}

bean
将该class属性保留为空,并在factory-bean属性中指定当前容器中bean的名称,该容器包含要调用创建对象的实例方法

<bean id="exampleBeanStaticFactory " class="com.woniu.spring.test.ExampleBeanStaticFactory ">
</bean>

<bean id="createExampleBean1" factory-bean="exampleBeanStaticFactory " factory-method="createExampleBean1"/>

<bean id="createExampleBean2" factory-bean="exampleBeanStaticFactory " factory-method="createExampleBean1"/>

测试类

public void SpringBeansTest() {
        ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");  
        ExampleBean createExampleBean1 = (ExampleBean) beans.getBean("createExampleBean1");
        ExampleBean createExampleBean2 = (ExampleBean) beans.getBean("createExampleBean2");
        createExampleBean1.print("实例工厂方法一");
        createExampleBean2.print("实例工厂方法二");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值