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类型!