Spring 自学系列之IOC-9【bean的生命周期】

53 篇文章 1 订阅

spring中bean是有生命周期的从装入context开始,到context被destroy结束。分别对应init-method 和destroy-methd 方法。

(1)init-method是bean被构造完成之后放入conext时需要执行的方法;

(2)destroy-methd 是cotext被destroy时,bean也就不复存在了,也就是在destroy之前所应该执行的方法。

(3)注意:因为这些方法默认该bean在context只出现一次,也就是说默认该bean是单例,所以这两个方法不要和prototype一起用(了解)

例子如下所示:

<?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-2.5.xsd">

  <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
	
  <bean id="userService" class="com.bjsxt.service.UserService" init-method="init" destroy-method="destroy" scope="prototype">
  	<!-- 
  	<property name="userDAO" ref="u" />
  	 -->
  	 <constructor-arg>
  	 	<ref bean="u"/>
  	 </constructor-arg>
  </bean>
  

</beans>
如上图所示 这两个方法不要和prototype一起用的时候,就会报错,所以scope应为singleton类型!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值