spring bean建立細節

鬆門一枝花發表於2016-05-06


1) 物件建立:

單例/多例
    scope="singleton", 預設值,即預設是單例【service/dao/工具類】
   scope="prototype", 多例;【Action物件】

2) 什麼時候建立?

  scope="prototype"  在用到物件的時候,才建立物件。
  scope="singleton"  在啟動(容器初始化之前), 就已經建立了bean,且整個應用只有一個。

3)是否延遲建立

 lazy-init="false"  預設為false,  不延遲建立,即在啟動時候就建立物件
 lazy-init="true"   延遲初始化, 在用到物件的時候才建立物件
  (lazy-init只對單例有效)       

4) 建立物件之後,初始化/銷燬

 init-method="init_user"  【對應物件的init_user方法,在物件建立之後執行 】
  destroy-method="destroy_user"  

【在呼叫容器物件的destriy方法時候執行,(容器用實現類),scope="singleton" 時有效】


<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	<bean id="userId" class="b_bean.User" scope="singleton" lazy-init="false"
		init-method="init_user" destroy-method="destroy_user"></bean>
		
</beans>      

  


package b_bean;

public class User {
	private int id;
	private String name;

	public User() {
		System.out.println("User物件建立....");
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void init_user(){
		System.out.println("init_user.....");
	}
	
	public void destroy_user(){
		System.out.println("destroy_user.....");
	}

}

package b_bean;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CreateBean {
	
	@Test
	public void test(){
		//ApplicationContext context=new ClassPathXmlApplicationContext("b_bean/applicationContext.xml");
		//為了測試destroy-method,介面沒有方法
		ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("b_bean/applicationContext.xml");
		System.out.println("ApplicationContext容器物件建立....");
		
		User user1=(User) context.getBean("userId");
		User user2=(User) context.getBean("userId");
		System.out.println(user1);
		System.out.println(user2);
		
		context.destroy();
	}
}



相關文章