欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring中bean实例化的三种方式:默认构造、静态工厂、实例工厂

程序员文章站 2022-03-03 11:24:48
...

1. 默认构造方式:必须提供默认构造

<bean id="bean id" class="工厂全限定类名"></bean>

以Studnet类为例

public class Student {
	
	private int id;
	private String name;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
		
}

applicationContext.xml配置

<bean id="Student" class="com.wuwl.entity.Student">
	<property name="id" value="520"></property>
	<property name="name" value="tom"></property>
	<property name="age" value="13"></property>
</bean>

测试方法

	public static void testStudent() {
		 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
		 Student student = ac.getBean("Student", Student.class);
		 System.out.println(student);
	}

2. 静态工厂:常用于spring整合其他框架(工具),所有方法必须是static

<bean id="bean id" class="工厂全限定类名"  factory-method="静态方法"></bean>

applicationContext.xml配置

<bean id="Student2" class="com.wuwl.entity.StudentStaticFactory" factory-method="getStudent">
	<!--**如果在此处不加上属性或对象,所有属性均为默认值,及时在对应的Student的bean中已经配置过了**-->
	<property name="id" value="520"></property>
	<property name="name" value="tom"></property>
	<property name="age" value="13"></property>
</bean>

测试方法

	public static void testStudentStaticFactory() {
		 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
		 Student student = ac.getBean("Student2", Student.class);
		 System.out.println(student);

	}

3. 实例工厂:必须现有工厂实例对象,再通过实例对象创建对象,提供所有的方法都必须是非静态方法

applicationContext.xml配置

<!--创建工厂实例-->
<bean id="StudentFactory" class="com.wuwl.entity.StudentFactory"></bean>
<!--创建对象-->
<bean id="Student1" factory-bean="StudentFactory" factory-method="getStudent">
	<!--**如果在此处不加上属性或对象,所有属性均为默认值,及时在对应的Student的bean中已经配置过了**-->
	<property name="id" value="520"></property>
	<property name="name" value="tom"></property>
	<property name="age" value="13"></property>
	</bean>

测试方法

public static void testStudentFactory() {
		 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
		 Student student = ac.getBean("Student1", Student.class);
		 System.out.println(student);
	}