通过优锐课核心java学习笔记中,我们可以看到解释Spring框架中bean的生命周期,码了很多专业的相关知识, 分享给大家参考学习。
Bean的生命周期:
Bean的定义——Bean的初始化——Bean的使用——Bean的销毁
Bean的定义
Bean 是 spring 装配的组件模型,一切实体类都可以配置成一个 Bean ,进而就可以在任何其他的 Bean 中使用,一个 Bean 也可以不是指定的实体类,这就是抽象 Bean 。
Bean的初始化
Spring中bean的初始化回调有两种方法
一种是在配置文件中声明init-method=“init”,然后在一个实体类中用init()方法来初始化
另一种是实现InitializingBean接口,覆盖afterPropertiesSet()方法。
第一种:
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="init-one" class="org.spring.test.BeanInitDemo1" init-method="init">
<property name="message" value="这里是配置文件中为message赋值"></property>
</bean>
</beans>
BeanInitDemo1类:
package org.spring.test;
public class BeanInitDemo1 {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void init(){
this.setMessage("这里是init()方法初始化设值");
}
}
测试类:
package org.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public