一、构造器实例化——spring容器通过Bean对应的类中默认的构造函数来实例化
- 导包
- 创建配置文件applicationContext.xml;
- 测试:有两种方法
- 使用范围:只要对应的类是普通类(非abstract),并且有无参的构造方法即可
例如:User实体类
public class User {
private static User user = new User();
// 私有构造方法
private User() {
System.out.println("构造方法");
}
public static User getInstance() {
return user;
}
}
配置文件:
<!-- 配置User实例 -->
<bean id="user" class="entity.User"></bean>
测试:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import entity.User;
public class Test1 {
public static void main(String[] args) {
// 创建spring容器
AbstractApplicationContext ac = new ClassPathXmlApplicationContext(
"applicationContext.xml");
// 获取User实例
//第一种方法:
// User user = (User)ac.getBean("user");// 强制转换
// System.out.println(user);
// 第二种方法:
User user = ac.getBean("user", User.class);
System.out.println(user);
二、静态工厂方式实例化——相对于使用构造方法,需要配置factory-method属性
- 用Calendar来举例:
配置文件:<bean id="calendar" class="java.util.Calendar" factory-method="getInstance"></bean>
测试:
Calendar calendar = ac.getBean("calendar", Calendar.class);
System.out.println(calendar);
适用场景:该类可能没有无参的构造方法,但是该类存在某个静态的无参方法,可以返回该类的对象。注意:要创建对象的类和提供静态方法的类,必须是同一个类。
三、实例工厂方式实例化——
- 创建person类
public class Person {
private int age = 10;
public Person() {
System.out.println("Person的构造方法");
}
public void init() {
System.out.println("Person的init方法");
}
public void destroy() {
System.out.println("Person的destrory方法");
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 创建PersonFactory类
public class PersonFactory {
public Person getPerson() {
return new Person();
}
}
- 配置该Bean
<bean id="personFactory" class="entity.PersonFactory"></bean>
<bean id="person" factory-bean="personFactory" factory-method="getPerson"
scope="prototype" init-method="init" destroy-method="destroy"></bean>
- 测试类
Person person1 = ac.getBean("person", Person.class);
System.out.println(person1.getAge());
总结:当工厂不是静态方法,或工厂方法所在类与需要的类并不是同一个,则需要使用实例工厂方法来获取对象。使用范围:另外有个类的方法(非静态)可以用于生产对象。在调用非静态方法之前,必须先创建该类的对象,所以先配置工厂。
四、Spring管理Bean的作用域
- 默认的单例模式singleton:在整个springIOC容器中,随着容器初始化而实例化,全局只有一个实例,无论多少个bean引用,始终指向同一个对象;
- 原型模式prototype():在使用的时候被实例化,每次通过spring容器获取prototype定义的bean时,容器都会创建一个新的bean。
五、通过Spring管理bean的生命周期
- 单例对象singleton:
- 创建:在spring容器初始化时创建。如果设置了init - method属性,则在创建以后调用初始化方法;
- 使用:返回的同一个对象;
- 销毁:关闭时,spring自动销毁单例对象,如果指定了destroy - method 属性,则会在销毁之前执行销毁方法。init-method属性,则在创建对象
- 多例对象prototype:
- 创建:调用getBean方法时创建。如果设置了init - method属性,则在创建以后调用初始化方法;
- 使用:每次返回新对象;
- 销毁:spring不管!
end.