Spring1.1——基于xml的bean装配的三种实例化方式

JAVAWEB框架学习文章索引点这里
三种实例化方式:
1,默认构造(类中必须有默认构造方法)
2,静态工厂(常用于与spring整合其他框架,所有方法必须是静态的)
3,实例工厂(必须现有工厂实例对象,然后用工厂实例对象创建bean,所有的方法必须是非静态的)

默认情况下是单例,也就是获取两次对象实际上是统一个。

<bean id="Car" class="com.c_Instant1.Car" scope="singleton"></bean>

改为多例方式

<bean id="Car" class="com.c_Instant1.Car" scope="prototype"></bean>

简单默认构造例子:
用于实例化的对象:

public class Car {
    public void run() {
        System.out.println("car run");
    }
}

配置文件:

<?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.xsd">
    <bean id="Car" class="com.c_Instant1.Car"></bean>
</beans>

测试类:

package com.c_Instant1;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test1() {
        String xmlPath = "com/c_Instant1/beans.xml";
        ApplicationContext appct = new ClassPathXmlApplicationContext(xmlPath);

        Car car = appct.getBean("Car", Car.class);
        car.run();
    }
}

结果:

car run

简单静态工厂例子
自定义工厂:

package com.c_Instant2;

public class MyFactory {
    public static Car getCar() {
        System.out.println("静态工厂");
        return new Car();
    }
}

配置文件:

<!-- 
        class指定静态工厂完整类名
        指定实例化对象的静态方法
     -->
    <bean id="Car" class="com.c_Instant2.MyFactory" factory-method="getCar"></bean>

测试类:

    @Test
    public void test1() {
        String xmlPath = "com/c_Instant2/beans.xml";
        ApplicationContext appct = new ClassPathXmlApplicationContext(xmlPath);
        Car car = appct.getBean("Car", Car.class);
        car.run();
    }

结果:

静态工厂
car run

实例工厂:
自定义实例工厂类:

package com.c_Instant3;

public class MyFactory {
    public Car getCar() {
        System.out.println("实例工厂");
        return new Car();
    }
}

配置文件:

<!-- 配置工厂 -->
    <bean id="MyFactory" class="com.c_Instant3.MyFactory"></bean>
    <!-- 配置工厂对应的实例化对象 -->
    <bean id="Car" factory-bean="MyFactory" factory-method="getCar"></bean>

测试类:

    @Test
    public void test1() {
        String xmlPath = "com/c_Instant3/beans.xml";
        ApplicationContext appct = new ClassPathXmlApplicationContext(xmlPath);
        Car car = appct.getBean("Car", Car.class);
        car.run();
    }

结果:

实例工厂
car run

猜你喜欢

转载自blog.csdn.net/smallhc/article/details/81228218