Spring中bean生命週期(淺顯易懂)
1、網上下的圖,以供參考
2、
/**
* 建立一個測試類的UserService
* @author lion
*
*/
public class UserService {
private String username;//使用者名稱
private String password;//密碼
/**
* 以下方法為了方便測試、bean生命週期過程的執行順序,事先打亂方法輸出順序
*/
public void destroy(){
System.out.println("---destory方法 -----");
}
public void init(){
System.out.println("---初始化方法 -----");
}
public UserService(){
System.out.println("---構造方法 -----");
}
public void setUsername(String username) {
this.username = username;
System.out.println("---setName方法-----");
}
}
/**
* 建立一個 TestUserServlet類
*/
@WebServlet("/TestUserServlet")
public class TestUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestUserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
UserService userService =(UserService) wac.getBean("userservice");//呼叫userService這個bean,檢視列印輸
}
}
3、配置檔案
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd " >
<!--注意測試生命週期的時候,需要配置init-method,destroy-method-->
<bean id="userservice" class="cn.web.neusoft.service.UserService" init-method="init" destroy-method="destroy">
<property name="username" value="pyc" />
<property name="password" value="123" />
</bean>
</beans>
列印輸出結果:
------參考輸出資訊,可以看出bean的生命週期幾個重要方法的執行順序---------------------------
--------構造方法---------
---------setName方法-----------------
---------init方法----------------------(由init-method屬性指定)
//如果有功能方法 如login(),輸出在初始化方法init()方法後
---------destory方法--------------- (銷燬方法)
以上大家可以測試一下,我試過沒問題。