package com.yiibai.customer.services; public class CustomerService { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
<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="customerService" class="com.yiibai.customer.services.CustomerService" /> </beans>
執行結果:
package com.tw511.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.customer.services.CustomerService; public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"}); CustomerService custA = (CustomerService)context.getBean("customerService"); custA.setMessage("Message by custA"); System.out.println("Message : " + custA.getMessage()); //retrieve it again CustomerService custB = (CustomerService)context.getBean("customerService"); System.out.println("Message : " + custB.getMessage()); } }
輸出結果
Message : Message by custA Message : Message by custA
由於 bean 的 「CustomerService' 是單例作用域,第二個通過提取」custB「將顯示訊息由 」custA' 設定,即使它是由一個新的 getBean()方法來提取。在單例中,每個Spring IoC容器只有一個範例,無論多少次呼叫 getBean()方法獲取它,它總是返回同一個範例。
<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="customerService" class="com.yiibai.customer.services.CustomerService" scope="prototype"/> </beans>
執行-執行
Message : Message by custA Message : null
package com.yiibai.customer.services; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope("prototype") public class CustomerService { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.yiibai.customer" /> </beans>