一、Bean的生命周期
Spring IOC容器可以管理Bean的生命周期,允许在Bean生命周期的特定点执行定制的任务。
Spring IOC容器对Bean的生命周期进行管理的过程如下:
(1).通过构造器或工厂方法创建Bean实例。
(2).为Bean的属性设置值和对其它Bean的引用。
(3).调用Bean的初始化方法。
(4).Bean的使用。
当容器关闭时,调用Bean的销毁方法。
在 Bean 的声明里设置 init-method 和 destroy-method 属性, 为 Bean 指定初始化和销毁方法。
示例:User实体类:
package com.atguigu.spring.helloworld;
import java.util.List;
public class User {
private String userName;
private List cars;
private String wifeName;
public String getWifeName() {
return wifeName;
}
public void setWifeName(String wifeName) {
System.out.println("设置wifeName属性。。。"+wifeName);
this.wifeName = wifeName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
System.out.println("设置userName属性。。。"+userName);
this.userName = userName;
}
public List getCars() {
return cars;
}
public void setCars(List cars) {
this.cars = cars;
}
// 构造方法
public User() {
System.out.println("正在使用构造方法 Construtor...");
}
@Override
public String toString() {
return "User [userName=" + userName + ", cars=" + cars + "]";
}
// 初始化方法
public void init(){
System.out.println("init method...");
}
// 销毁方法
public void destroy(){
System.out.println("destroy method...");
}
}
配置文件beans-auto.xml:
boy " class="com.atguigu.spring.helloworld.User" init-method="init" destroy-method="destroy">
测试Main函数:
package com.atguigu.spring.ref;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.spring.helloworld.User;
public class Main {
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-auto.xml");
//测试 spEL
User boy = (User) ctx.getBean("boy");
System.out.println(boy);
ctx.close();
}
}
测试结果:
说明:首先通过构造函数来创建bean的实例,然后通过setter方法设置属性,在使用bean实例之前,执行了init初始化方法,使用之后又执行了destroy方法。
二、创建Bean的后置处理器
Bean后置处理允许在调用初始化方法前后对Bean进行额外的处理,Bean后置处理器对IOC容器的所有Bean实例逐一处理,而非单一实例。其典型应用是:检查Bean属性的正确性或根据特定的标准更改Bean的属性。
对Bean后置处理器而言,需要实现接口BeanPostProcessor,在初始化方法被调用前后,Spring将把每个Bean实例分别传递给上述接口的以下两个方法:
添加Bean后置处理器后,Spring IOC容器对Bean的生命周期管理的过程为:
- 通过构造器或工厂方法创建 Bean 实例
- 为 Bean 的属性设置值和对其他 Bean 的引用
- 将 Bean 实例传递给 Bean 后置处理器的 postProcessBeforeInitialization 方法
- 调用 Bean 的初始化方法
- 将 Bean 实例传递给 Bean 后置处理器的 postProcessAfterInitialization方法
- Bean 可以使用了
- 当容器关闭时, 调用 Bean 的销毁方法。
示例演示Bean的后置处理器:
先定义MyBeanPostProcessor类并实现BeanPostProcessor接口:
package com.atguigu.spring.ref;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import com.atguigu.spring.helloworld.User;
public class MyBeanPostProcessor implements BeanPostProcessor {
//该方法在 init 方法之后被调用
@Override
public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
if(arg1.equals("boy")){
System.out.println("postProcessAfterInitialization..." + arg0 + "," + arg1);
User user = (User) arg0;
user.setUserName("李大齐");
}
return arg0;
}
//该方法在 init 方法之前被调用
//可以工作返回的对象来决定最终返回给 getBean 方法的对象是哪一个, 属性值是什么
/**
* @param arg0: 实际要返回的对象
* @param arg1: bean 的 id 值
*/
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
if(arg1.equals("boy"))
System.out.println("postProcessBeforeInitialization..." + arg0 + "," + arg1);
return arg0;
}
}
bean-auto.xml文件中配置Bean的后置处理器bean,
main函数测试类在与上文相同,测试结果如下:
说明:和上面的测试结果对比可以看出,多了一个在bean初始化方法之前将 Bean 实例传递给 Bean 后置处理器的 postProcessBeforeInitialization 方法和在执行bean初始化方法之后将 Bean 实例传递给 Bean 后置处理器的 postProcessAfterInitialization方法
三、通过工厂方法创建Bean
3.1、静态工厂方法创建Bean
创建Car实体类:
package com.atguigu.spring.ref;
public class Car {
private String company;
private String brand;
private int maxSpeed;
private float price;
public Car() {
}
public Car(String company,float price) {
super();
this.company = company;
this.price = price;
}
@Override
public String toString() {
return "Car [company=" + company + ", brand=" + brand + ", maxSpeed="
+ maxSpeed + ", price=" + price + "]";
}
}
创建静态工厂方法:
package com.atguigu.spring.ref;
import java.util.HashMap;
import java.util.Map;
public class StaticCarFactory {
private static Map cars = new HashMap();
static {
cars.put("Audi", new Car("Audi", 300000));
cars.put("Ford", new Car("Ford", 500000));
}
// 静态工厂方法
public static Car getCar(String name) {
return cars.get(name);
}
}
bean-auto.xml配置静态工厂方法bean:
测试函数:
package com.atguigu.spring.ref;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-auto.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car+"**********");
ctx.close();
}
}
执行结果:
3.2、实例工厂方法创建Bean
实例工厂方法: 将对象的创建过程封装到另外一个对象实例的方法里. 当客户端需要请求对象时, 只需要简单的调用该实例方法而不需要关心对象的创建细节。
要声明通过实例工厂方法创建的 Bean
(1).在 bean 的 factory-bean 属性里指定拥有该工厂方法的 Bean
(2).在 factory-method 属性里指定该工厂方法的名称
(3).使用 construtor-arg 元素为工厂方法传递方法参数
也可以通过实现FactoryBean接口来创建Bean的实例:
创建UserBean并实现FactoryBean接口:
package com.atguigu.spring.ref;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.FactoryBean;
import com.atguigu.spring.helloworld.Car;
import com.atguigu.spring.helloworld.User;
public class UserBean implements FactoryBean{
/**
* 返回的 bean 的实例
*/
@Override
public User getObject() throws Exception {
User user = new User();
user.setUserName("abc");
user.setWifeName("ABC");
List cars = new ArrayList<>();
cars.add(new Car("ShangHai", "BuiKe", 180, 300000));
cars.add(new Car("ShangHai", "CRUZE", 130, 150000));
user.setCars(cars);
return user;
}
/**
* 返回的 bean 的类型
*/
@Override
public Class> getObjectType() {
return User.class;
}
/**
* 返回的 bean 是否为单例的
*/
@Override
public boolean isSingleton() {
return true;
}
}
bean-auto.xml文件中配置bean:
四、Bean的作用域
scope用来声明容器中的对象所应该处的限定场景或者说该对象的存活时间。
1、singleton
标记为拥有singleton的对象定义,在Spring的IOC容器中只存在一个实例,所有对该对象的引用将共享这个实例。该实例从容器启动,并因为第一次请求而初始化之后,将一直存活到容器退出。
2、prototype
拥有prototype的bean定义,容器在接到该类型对象的请求的时候,会每次都重新生成一个新的对象实例给请求方,虽然这种类型的对象的实例化以及属性设置等工作都是由容器负责的,但是只要准备完毕,并且对象实例返回给请求方之后,容器就不在拥有当前返回对象的引用。
3、request、session和global session
这三类只适用于Web应用程序,通常是与XmlWebApplicationContext共同使用。request:XmlWebApplicationContext会为每个http请求创建一个全新的request-processor对象供当前请求使用,当请求结束后,该对象实例的生命周期即告结束。request可以看做是prototype的一种特例,除了应用场景更加具体。
session:Spring容器会为每个独立的session创建属于他们自己的全新的对象实例,与request相比,除了拥有更长的存活时间,其他没什么差别。
global session:只在基于portlet的web应用程序中才有意义
源码下载:https://github.com/ablejava/Spring-IOC-Bean