1. 程式人生 > >Spring核心之2 SpringBean的作用域

Spring核心之2 SpringBean的作用域

2.Bean的作用域

當通過Spring容器建立一個Bean例項時,不僅可以完成Bean例項的例項化,還可以為Bean指定特定的作用域。

預設作用域為singleton單例模式

Spring支援如下5種作用域

2.1.singleton

singleton:單例模式,在整個Spring IoC容器中,使用singleton定義的Bean將只有一個例項

預設作用域為singleton單例模式

對於singleton作用域的Bean,每次請求該Bean都將獲得相同的例項。容器負責跟蹤Bean例項的狀態,負責維護Bean例項的生命週期行為;

<bean id="accountService" class
="com.foo.DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default) --> <bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

2.1.1.意圖

保證一個類僅有一個例項,並提供一個訪問它的全域性訪問點。

2.1.2.主要解決

一個全域性使用的類頻繁地建立與銷燬。

2.1.3.何時使用

當您想控制例項數目,節省系統資源的時候。

2.1.4.如何解決

判斷系統是否已經有這個單例,如果有則返回,如果沒有則建立。

2.1.5.關鍵程式碼

建構函式是私有的。

2.1.6.應用例項

1、一個黨只能有一個主席。

2、Windows 是多程序多執行緒的,在操作一個檔案的時候,就不可避免地出現多個程序或執行緒同時操作一個檔案的現象,所以所有檔案的處理必須通過唯一的例項來進行。

3、一些裝置管理器常常設計為單例模式,比如一個電腦有兩臺印表機,在輸出的時候就要處理不能兩臺印表機列印同一個檔案。

2.1.7.優點

1、在記憶體裡只有一個例項,減少了記憶體的開銷,尤其是頻繁的建立和銷燬例項(比如管理學院首頁頁面快取)。

2、避免對資源的多重佔用(比如寫檔案操作)。

2.1.8.缺點

沒有介面,不能繼承,與單一職責原則衝突,一個類應該只關心內部邏輯,而不關心外面怎麼樣來例項化。

2.1.9.使用場景

1、要求生產唯一序列號。

2、WEB 中的計數器,不用每次重新整理都在資料庫里加一次,用單例先快取起來。

3、建立的一個物件需要消耗的資源過多,比如 I/O 與資料庫的連線等。

2.1.10.注意事項

1、單例類只能有一個例項。

2、單例類必須自己建立自己的唯一例項。

3、單例類必須給所有其他物件提供這一例項。

4、getInstance() 方法中需要使用同步鎖 synchronized (Singleton.class) 防止多執行緒同時進入造成 instance 被多次例項化。

2.1.11 程式碼樣例

0.日誌輸出log4j.properties配置

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n 

1.Beans001.xml配置檔案

<?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-3.0.xsd">
    <!-- 用構造器去例項化bean -->
        <bean
        id="singletonExampleBean"
        class="com.gaoxinfu.demo.spring.example.bean.ExampleBean"/>
</beans>

2.ExampleBean

package com.gaoxinfu.demo.spring.example.bean;

import com.gaoxinfu.demo.base.Base;

public class ExampleBean extends Base{

	public ExampleBean() {
		logger.info("ExampleBean構造方法ExampleBean()例項化ExampleBean");
	}

	public void execute() {
		logger.info("ExampleBean方法execute()執行ExampleBean處理");
	}
}

3.ExampleBeanTest

@Test
public void singleton() {
	String beanConfig="Beans001.xml";
	ApplicationContext context =new ClassPathXmlApplicationContext(beanConfig);
	ExampleBean exampleBean01= context.getBean("singletonExampleBean",ExampleBean.class);
	ExampleBean exampleBean02= context.getBean("singletonExampleBean",ExampleBean.class);
	logger.info("exampleBean01==exampleBean02 結果為="+(exampleBean01==exampleBean02));
	
}

4.日誌輸出

StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
 StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
 StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
 ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@303bc257: startup date [Sun Feb 11 14:26:33 CST 2018]; root of context hierarchy
 StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
 StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
 StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
 XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [Beans001.xml]
 DefaultDocumentLoader - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
 PluggableSchemaResolver - Loading schema mappings from [META-INF/spring.schemas]
 PluggableSchemaResolver - Loaded schema mappings: {http://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd, http://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd, http://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd, http://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd, http://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd, http://www.springframework.org/schema/aop/spring-aop-3.0.xsd=org/springframework/aop/config/spring-aop-3.0.xsd, http://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd, http://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd, http://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd, http://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd, http://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd, http://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd, http://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-3.2.xsd, http://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd, http://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd, http://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd, http://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd, http://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd, http://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd, http://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd, http://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd, http://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd, http://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd, http://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd, http://www.springframework.org/schema/aop/spring-aop-3.2.xsd=org/springframework/aop/config/spring-aop-3.2.xsd, http://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd, http://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd, http://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd, http://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd, http://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd, http://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd, http://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd, http://www.springframework.org/schema/aop/spring-aop-2.5.xsd=org/springframework/aop/config/spring-aop-2.5.xsd, http://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd, http://www.springframework.org/schema/aop/spring-aop-3.1.xsd=org/springframework/aop/config/spring-aop-3.1.xsd, http://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd, http://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd, http://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd, http://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd, http://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd, http://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd}
 PluggableSchemaResolver - Found XML schema [http://www.springframework.org/schema/beans/spring-beans-3.0.xsd] in classpath: org/springframework/beans/factory/xml/spring-beans-3.0.xsd
 DefaultBeanDefinitionDocumentReader - Loading bean definitions
 XmlBeanDefinitionReader - Loaded 5 bean definitions from location pattern [Beans001.xml]
 ClassPathXmlApplicationContext - Bean factory for org.springframework.context.support.ClassPathXmlApplicationContext@303bc257: org.springframework.beans.factory.support.DefaultListableBeanFactory@1018f51f: defining beans [calendarobj1,calendarobj2,calendarobj3,calendarobj4,exampleBean]; root of factory hierarchy
 ClassPathXmlApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@2a8ddc4c]
 ClassPathXmlApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@2f60877b]
 DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1018f51f: defining beans [calendarobj1,calendarobj2,calendarobj3,calendarobj4,exampleBean]; root of factory hierarchy
 DefaultListableBeanFactory - Creating shared instance of singleton bean 'calendarobj1'
 DefaultListableBeanFactory - Creating instance of bean 'calendarobj1'
 DefaultListableBeanFactory - Eagerly caching bean 'calendarobj1' to allow for resolving potential circular references
 DefaultListableBeanFactory - Finished creating instance of bea