1. 程式人生 > >spring中bean的三種例項化方式

spring中bean的三種例項化方式

Bean的三種建立方式:

xml配置

<!-- 配置資源:把物件的建立交給spring來管理 -->
    <bean id="customerService" class="com.service.impl.CustomerServiceImpl"></bean>
    
    <!-- 配置使用靜態工廠建立bean物件 -->
	<bean id="staticCustomerService" class="com.factory.StaticFactory" factory-method="getCustomerService"
>
</bean> <!-- 配置使用例項工廠建立bean物件 --> <bean id="instanceFactory" class="com.factory.InstanceFactory"></bean> <bean id="instanceCustomerService" factory-bean="instanceFactory" factory-method="getCustomerService"></bean>

StaticFactory.java

public class StaticFactory
{ public static ICustomerService getCustomerService(){ return new CustomerServiceImpl(); } }

InstanceFactory.java

public class InstanceFactory {

	public ICustomerService getCustomerService(){
		return new CustomerServiceImpl();
	}
}

java程式碼使用

public static void main(String[] args) {
		ApplicationContext ac =
new ClassPathXmlApplicationContext("bean.xml"); ICustomerService cs1 = (ICustomerService) ac.getBean("xxx"); }
  • 1.呼叫預設無參建構函式建立,預設情況下,如果類中沒有預設無參建構函式,則建立失敗,會報異常

在第一種建立方式中,spring會到你所寫的class這個類中找到他的無參建構函式,並建立一個物件存在容器裡,通過id可以獲取到這個物件

  • 2.使用工廠中的方法建立物件:需要使用bean標籤的factory-method屬性,指定靜態工廠中建立物件的方法

第二種方法中多了個工廠類,工廠類中有個靜態get方法來返回一個class物件,在xml配置的時候用factory-method修飾這個get方法,此時spring會讓工程類呼叫factory-method中指定的方法,並且返回給指定的id這個key存起來

  • 3.使用例項工廠的方法建立

與第二種方法類似,但是這個工廠類的get方法不是靜態的,這個時候就要通過bean標籤先建立一個工廠類物件,然後用這個工廠類物件呼叫factory-method中的方法獲取到物件