面试题解答系列:解释Spring框架中bean的生命周期

通过优锐课核心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
  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值