IOC容器中Bean的生命周期

Spring IOC容器可以管理Bean的生命周期,Spring允许在Bean生命周期的特定点执行定制的任务。

Spring IOC容器对Bean的生命周期进行管理的过程:

-通过构造器或工厂方法创建Bean实例

-为Bean的属性值和对其他Bean的引用

-调用Bean的初始化方法

-Bean可以使用了

-当容器关闭时,调用Bean的销毁方法

在Bean的声明里设置init-method和destroy-method属性,为Bean指定初始化和销毁方法。

下面看代码

package logan.spring.study.cycle;

public class Car {

    public Car() {
// TODO Auto-generated constructor stub
System.out.println("Car's Constructor...");
} private String brand; public void setBrand(String brand) {
this.brand = brand;
} public void init(){
System.out.println("init...");
} public void destroy(){
System.out.println("destroy...");
} }

配置文件

<?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="logan.spring.study.cycle.Car"
init-method="init"
destroy-method="destroy">
<property name="brand" value="Audi"></property>
</bean> </beans>

测试代码

package logan.spring.study.cycle;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
// TODO Auto-generated method stub ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cycle.xml"); Car car = (Car) ctx.getBean("car"); System.out.println(car); ctx.close(); } }

输出结果

五月 21, 2017 10:21:56 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 10:21:56 CST 2017]; root of context hierarchy
五月 21, 2017 10:21:56 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-cycle.xml]
Car's Constructor...
init...
logan.spring.study.cycle.Car@523884b2
五月 21, 2017 10:21:56 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 10:21:56 CST 2017]; root of context hierarchy
destroy...

创建Bean后置处理器

Bean后置处理器允许在调用初始化方法前后对Bean进行而外的处理。

Bean后置处理器对IOC容器里的所有Bean实例逐一处理,而非单一的实例,器典型应用是:检查Bean属性的正确性或者根据特定的标准更改Bean的属性。

对Bean后置处理器而言,需要实现Interface BeanPostProcessor接口,在初始化方法被调用前后,Spring将会把每个Bean实例分别传递给上述接口的一下两个方法:

postProcessAfterInitialization(Object bean,String beanName)

postProcessBeforeinitialization(Object bean, String beanName)

添加Bean后置处理器后Bean的生命周期

Spring IOC容器对Bean的生命周期进行管理的过程:

-通过构造器或者工厂方法创建Bean实例

-为Bean的属性设置值和对其他Bean的引用

-将Bean实例传递给Bean后置处理器的postProcessBeforeInitialization方法

-调用Bean的初始化方法

-将Bean实例传递给Bean后置处理器的postProcessAfterInitialization方法

-Bean可以使用了

-当关不容器时,调用Bean的销毁方法。

看下面代码:

package logan.spring.study.cycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcess implements BeanPostProcessor { @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessAfterInitialization" + ", " + bean + ", " + beanName);
return bean;
} @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessBeforeInitialization" + ", " + bean + ", " + beanName);
return bean;
} }
<?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="logan.spring.study.cycle.Car"
init-method="init"
destroy-method="destroy">
<property name="brand" value="Audi"></property>
</bean> <bean class="logan.spring.study.cycle.MyBeanPostProcess"></bean> </beans>

下面是输出结果:

五月 21, 2017 10:44:40 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 10:44:40 CST 2017]; root of context hierarchy
五月 21, 2017 10:44:40 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-cycle.xml]
Car's Constructor...
postProcessBeforeInitialization, logan.spring.study.cycle.Car@4b9e13df, car
init...
postProcessAfterInitialization, logan.spring.study.cycle.Car@4b9e13df, car
logan.spring.study.cycle.Car@4b9e13df
五月 21, 2017 10:44:41 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 10:44:40 CST 2017]; root of context hierarchy
destroy...

BeanProcessor很强大,可以偷梁换柱,如下代码:

package logan.spring.study.cycle;

public class Car {

    public Car() {
// TODO Auto-generated constructor stub
System.out.println("Car's Constructor...");
} private String brand; public void setBrand(String brand) {
this.brand = brand;
} public void init(){
System.out.println("init...");
} public void destroy(){
System.out.println("destroy...");
} @Override
public String toString() {
return "Car [brand=" + brand + "]";
} }
package logan.spring.study.cycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcess implements BeanPostProcessor { @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessAfterInitialization" + ", " + bean + ", " + beanName);
Car car = new Car();
car.setBrand("Ford");
return car;
} @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessBeforeInitialization" + ", " + bean + ", " + beanName);
return bean;
} }

下面是输出结果:

五月 21, 2017 10:49:29 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 10:49:29 CST 2017]; root of context hierarchy
五月 21, 2017 10:49:29 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-cycle.xml]
Car's Constructor...
postProcessBeforeInitialization, Car [brand=Audi], car
init...
postProcessAfterInitialization, Car [brand=Audi], car
Car's Constructor...
Car [brand=Ford]
五月 21, 2017 10:49:29 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 10:49:29 CST 2017]; root of context hierarchy
destroy...

Spring入门第十一课的更多相关文章

  1. Spring入门第六课

    XML配置里的Bean自动装配 Spring IOC容器可以自动装配Bean.需要做的仅仅是在<bean>的autowire属性里指定自动装配的模式 ByType(根据类型自动装配):若I ...

  2. Spring入门第五课

    集合属性 在Spring中可以通过一组内置的xml标签(如:<list>,<set>,<map>)来配置集合属性. 配置java.util.List类型的属性,需要 ...

  3. Spring入门第四课

    注入参数详解:null值和级联属性 可以使用专用的<null/>元素标签为Bean的字符串或其他对象类型的属性注入null值. 和Struts,Hiberante等框架一样,Spring支 ...

  4. Spring入门第三课

    属性注入 属性注入就是通过setter方法注入Bean的属性值或依赖的对象. 属性植入使用<property>元素,使用name属性指定Bean的属性名称,value属性或者<val ...

  5. Spring入门第十三课

    通过FactoryBean来配置Bean package logan.spring.study.factoryBean; public class Car { private String brand ...

  6. Spring入门第十课

    Spring表达式语言:SpEL Spring表达式语言(简称SpEL)是一个支持运行时查询和操作对象图的强大的表达式语言. 语法类似于EL:SpEL使用#{...}作为定界符,所有在大括号中的字符都 ...

  7. Spring入门第八课

    看如下代码 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http:// ...

  8. Spring入门第七课

    Bean之间的关系:继承和依赖. 继承Bean配置 Spring允许继承bean的配置,被继承的bean称为父bean,继承这个父bean的Bean称为子Bean. 子Bean从父Bean中继承配置, ...

  9. Spring入门第十七课

    AOP编程 问题: 代码混乱: 越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同事还必须兼顾其他多个关注点. 代码分散:以日志需求为例,只是为了满足这个单 ...

随机推荐

  1. COGS410. [NOI2009] 植物大战僵尸

    410. [NOI2009] 植物大战僵尸 ★★★   输入文件:pvz.in   输出文件:pvz.out   简单对比时间限制:2 s   内存限制:512 MB [问题描述] Plants vs ...

  2. Nodejs 中常见的加密算法:RSA(1)

    Linux用户(以Ubuntu为例) $ openssl 进入OpenSSL程序 OpenSSL> genrsa -out rsa_private_key.pem 1024 生成私钥 OpenS ...

  3. Map总结--HashMap/HashTable/TreeMap/WeakHashMap使用场景分析(转)

    首先看下Map的框架图 1.Map概述 1.Map是键值对映射的抽象接口 2.AbstractMap实现了Map中绝大部分的函数接口,它减少了“Map实现类”的重复编码 3.SortedMap有序的“ ...

  4. 【windows】如何让一个程序开机自启动

    windows的开机自启动也是将一个程序放在文件夹下即可,将应用程序或者快捷方式放在如下文件夹下,即可实现开机自启动 C:\ProgramData\Microsoft\Windows\Start Me ...

  5. Java for LeetCode 121 Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...

  6. sourceSet

    android { sourceSets { main{ manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources ...

  7. Ruby操作数据库基本步骤

    1.rails g model university name:string 2.model has_many :colleges belongs_to :university has_one :us ...

  8. NET LOCALGROUP命令详解(将用户添加到管理员组等)

    NET LOCALGROUP [groupname [/COMMENT:"text"]] [/DOMAIN] groupname {/ADD [/COMMENT:"tex ...

  9. Centos虚拟机克隆后的ip配置

    1. rm -rf /etc/udev/rules.d/-persistent-net.rules 2. 重启,然后: vi /etc/udev/rules.d/70-persistent-net.r ...

  10. gVIM+zencoding快速开发HTML/CSS/JS(适用WEB前端)

    一.真正解决了UTF-8中文乱码的各种问题(菜单乱码,内容乱码,提示信息乱码),不用担心WIN用默认编码写的东西在Linux乱码,或在Linux(zh_CN.UTF-8时)写的东西在WIN下乱码.在A ...