欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
Spring源代碼解析(一):IOC容器

Spring源代碼解析(一):IOC容器

在認真學(xué)習Rod.Johnson的三部曲之一:< >,順便也看了看源代碼想知道個(gè)究竟,拋磚引玉,有興趣的同志一起討論研究吧!

  以下內容引自博客:http://jiwenke-spring.blogspot.com/,歡迎指導:)

  在Spring中,IOC容器的重要地位我們就不多說(shuō)了,對于Spring的使用者而言,IOC容器實(shí)際上是什么呢?我們可以說(shuō)BeanFactory就是我們看到的IoC容器,當然了Spring為我們準備了許多種IoC容器來(lái)使用,這樣可以方便我們從不同的層面,不同的資源位置,不同的形式的定義信息來(lái)建立我們需要的IoC容器。

  在Spring中,最基本的IOC容器接口是BeanFactory - 這個(gè)接口為具體的IOC容器的實(shí)現作了最基本的功能規定 - 不管怎么著(zhù),作為IOC容器,這些接口你必須要滿(mǎn)足應用程序的最基本要求:

  代碼

public interface BeanFactory {  

  //這里是對FactoryBean的轉義定義,因為如果使用bean的名字檢索FactoryBean得到的對象是工廠(chǎng)生成的對象,  

  //如果需要得到工廠(chǎng)本身,需要轉義     

  String FACTORY_BEAN_PREFIX = "&";  

  //這里根據bean的名字,在IOC容器中得到bean實(shí)例,這個(gè)IOC容器就是一個(gè)大的抽象工廠(chǎng)?! ?/p>

  Object getBean(String name) throws BeansException;  

  //這里根據bean的名字和Class類(lèi)型來(lái)得到bean實(shí)例,和上面的方法不同在于它會(huì )拋出異常:如果根據名字取得的bean實(shí)例的Class類(lèi)型和需要的不同的話(huà)?! ?/p>

  Object getBean(String name, Class requiredType) throws BeansException;  

  //這里提供對bean的檢索,看看是否在IOC容器有這個(gè)名字的bean  

  boolean containsBean(String name);  

  //這里根據bean名字得到bean實(shí)例,并同時(shí)判斷這個(gè)bean是不是單件  

  boolean isSingleton(String name) throws NoSuchBeanDefinitionException;  

  //這里對得到bean實(shí)例的Class類(lèi)型  

  Class getType(String name) throws NoSuchBeanDefinitionException;  

  //這里得到bean的別名,如果根據別名檢索,那么其原名也會(huì )被檢索出來(lái)  

  String[] getAliases(String name);  

} 

在BeanFactory里只對IOC容器的基本行為作了定義,根本不關(guān)心你的bean是怎樣定義怎樣加載的 - 就像我們只關(guān)心從這個(gè)工廠(chǎng)里我們得到到什么產(chǎn)品對象,至于工廠(chǎng)是怎么生產(chǎn)這些對象的,這個(gè)基本的接口不關(guān)心這些。如果要關(guān)心工廠(chǎng)是怎樣產(chǎn)生對象的,應用程序需要使用具體的IOC容器實(shí)現- 當然你可以自己根據這個(gè)BeanFactory來(lái)實(shí)現自己的IOC容器,但這個(gè)沒(méi)有必要,因為Spring已經(jīng)為我們準備好了一系列工廠(chǎng)來(lái)讓我們使用。比如XmlBeanFactory就是針對最基礎的BeanFactory的IOC容器的實(shí)現 - 這個(gè)實(shí)現使用xml來(lái)定義IOC容器中的bean。

  Spring提供了一個(gè)BeanFactory的基本實(shí)現,XmlBeanFactory同樣的通過(guò)使用模板模式來(lái)得到對IOC容器的抽象- AbstractBeanFactory,DefaultListableBeanFactory這些抽象類(lèi)為其提供模板服務(wù)。其中通過(guò)resource 接口來(lái)抽象bean定義數據,對Xml定義文件的解析通過(guò)委托給XmlBeanDefinitionReader來(lái)完成。下面我們根據書(shū)上的例子,簡(jiǎn)單的演示IOC容器的創(chuàng )建過(guò)程:

  代碼

ClassPathResource res = new ClassPathResource("beans.xml");  

DefaultListableBeanFactory factory = new DefaultListableBeanFactory();  

XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);  

reader.loadBeanDefinitions(res); 

  這些代碼演示了以下幾個(gè)步驟:

  1. 創(chuàng )建IOC配置文件的抽象資源

  2. 創(chuàng )建一個(gè)BeanFactory

  3. 把讀取配置信息的BeanDefinitionReader,這里是XmlBeanDefinitionReader配置給BeanFactory

  4. 從定義好的資源位置讀入配置信息,具體的解析過(guò)程由XmlBeanDefinitionReader來(lái)完成,這樣完成整個(gè)載入bean定義的過(guò)程。我們的IoC容器就建立起來(lái)了。在BeanFactory的源代碼中我們可以看到:

代碼

public class XmlBeanFactory extends DefaultListableBeanFactory {  

  //這里為容器定義了一個(gè)默認使用的bean定義讀取器  

  private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);  

  public XmlBeanFactory(Resource resource) throws BeansException {  

    this(resource, null);  

  }  

  //在初始化函數中使用讀取器來(lái)對資源進(jìn)行讀取,得到bean定義信息?! ?/p>

  public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {  

    super(parentBeanFactory);  

    this.reader.loadBeanDefinitions(resource);  

  } 

  我們在后面會(huì )看到讀取器讀取資源和注冊bean定義信息的整個(gè)過(guò)程,基本上是和上下文的處理是一樣的,從這里我們可以看到上下文和 XmlBeanFactory這兩種IOC容器的區別,BeanFactory往往不具備對資源定義的能力,而上下文可以自己完成資源定義,從這個(gè)角度上看上下文更好用一些。

  仔細分析Spring BeanFactory的結構,我們來(lái)看看在BeanFactory基礎上擴展出的ApplicationContext - 我們最常使用的上下文。除了具備BeanFactory的全部能力,上下文為應用程序又增添了許多便利:

  * 可以支持不同的信息源,我們看到ApplicationContext擴展了MessageSource

  * 訪(fǎng)問(wèn)資源 , 體現在對ResourceLoader和Resource的支持上面,這樣我們可以從不同地方得到bean定義資源

  * 支持應用事件,繼承了接口A(yíng)pplicationEventPublisher,這樣在上下文中引入了事件機制而B(niǎo)eanFactory是沒(méi)有的。

ApplicationContext允許上下文嵌套 - 通過(guò)保持父上下文可以維持一個(gè)上下文體系 - 這個(gè)體系我們在以后對Web容器中的上下文環(huán)境的分析中可以清楚地看到。對于bean的查找可以在這個(gè)上下文體系中發(fā)生,首先檢查當前上下文,其次是父上下文,逐級向上,這樣為不同的Spring應用提供了一個(gè)共享的bean定義環(huán)境。這個(gè)我們在分析Web容器中的上下文環(huán)境時(shí)也能看到。

  ApplicationContext提供IoC容器的主要接口,在其體系中有許多抽象子類(lèi)比如AbstractApplicationContext為具體的BeanFactory的實(shí)現,比如FileSystemXmlApplicationContext和 ClassPathXmlApplicationContext提供上下文的模板,使得他們只需要關(guān)心具體的資源定位問(wèn)題。當應用程序代碼實(shí)例化 FileSystemXmlApplicationContext的時(shí)候,得到IoC容器的一種具體表現 - ApplicationContext,從而應用程序通過(guò)ApplicationContext來(lái)管理對bean的操作。

  BeanFactory 是一個(gè)接口,在實(shí)際應用中我們一般使用ApplicationContext來(lái)使用IOC容器,它們也是IOC容器展現給應用開(kāi)發(fā)者的使用接口。對應用程序開(kāi)發(fā)者來(lái)說(shuō),可以認為BeanFactory和ApplicationFactory在不同的使用層面上代表了SPRING提供的IOC容器服務(wù)。

  下面我們具體看看通過(guò)FileSystemXmlApplicationContext是怎樣建立起IOC容器的, 顯而易見(jiàn)我們可以通過(guò)new來(lái)得到IoC容器:

  代碼

  ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);  

  調用的是它初始化代碼:

  代碼

public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)  

    throws BeansException {  

  super(parent);  

  this.configLocations = configLocations;  

  if (refresh) {  

    //這里是IoC容器的初始化過(guò)程,其初始化過(guò)程的大致步驟由AbstractApplicationContext來(lái)定義  

    refresh();  

  }  

}

refresh的模板在A(yíng)bstractApplicationContext:

  代碼

public void refresh() throws BeansException, IllegalStateException {  

  synchronized (this.startupShutdownMonitor) {  

    synchronized (this.activeMonitor) {  

      this.active = true;  

    }  

    // 這里需要子類(lèi)來(lái)協(xié)助完成資源位置定義,bean載入和向IOC容器注冊的過(guò)程  

    refreshBeanFactory();  

    ............  

}  

  這個(gè)方法包含了整個(gè)BeanFactory初始化的過(guò)程,對于特定的FileSystemXmlBeanFactory,我們看到定位資源位置由refreshBeanFactory()來(lái)實(shí)現:

  在A(yíng)bstractXmlApplicationContext中定義了對資源的讀取過(guò)程,默認由XmlBeanDefinitionReader來(lái)讀?。?

  代碼

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {  

  // 這里使用XMLBeanDefinitionReader來(lái)載入bean定義信息的XML文件  

  XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);  

  //這里配置reader的環(huán)境,其中ResourceLoader是我們用來(lái)定位bean定義信息資源位置的  

  ///因為上下文本身實(shí)現了ResourceLoader接口,所以可以直接把上下文作為ResourceLoader傳遞給XmlBeanDefinitionReader  

  beanDefinitionReader.setResourceLoader(this);  

  beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));  

  initBeanDefinitionReader(beanDefinitionReader);  

  //這里轉到定義好的XmlBeanDefinitionReader中對載入bean信息進(jìn)行處理  

  loadBeanDefinitions(beanDefinitionReader);  

} 

轉到beanDefinitionReader中進(jìn)行處理:

  代碼

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {  

  Resource[] configResources = getConfigResources();  

  if (configResources != null) {  

    //調用XmlBeanDefinitionReader來(lái)載入bean定義信息?! ?/p>

    reader.loadBeanDefinitions(configResources);  

  }  

  String[] configLocations = getConfigLocations();  

  if (configLocations != null) {  

    reader.loadBeanDefinitions(configLocations);  

  }  

} 

  而在作為其抽象父類(lèi)的AbstractBeanDefinitionReader中來(lái)定義載入過(guò)程:

  代碼

public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {  

//這里得到當前定義的ResourceLoader,默認的我們使用DefaultResourceLoader  

ResourceLoader resourceLoader = getResourceLoader();  

.........//如果沒(méi)有找到我們需要的ResourceLoader,直接拋出異?! ?/p>

  if (resourceLoader instanceof ResourcePatternResolver) {  

    // 這里處理我們在定義位置時(shí)使用的各種pattern,需要ResourcePatternResolver來(lái)完成  

    try {  

      Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);  

      int loadCount = loadBeanDefinitions(resources);  

      return loadCount;  

    }  

   ........  

  }  

  else {  

    // 這里通過(guò)ResourceLoader來(lái)完成位置定位  

    Resource resource = resourceLoader.getResource(location);  

    // 這里已經(jīng)把一個(gè)位置定義轉化為Resource接口,可以供XmlBeanDefinitionReader來(lái)使用了  

    int loadCount = loadBeanDefinitions(resource);  

    return loadCount;  

  }  

} 

 當我們通過(guò)ResourceLoader來(lái)載入資源,別忘了了我們的GenericApplicationContext也實(shí)現了ResourceLoader接口:

  代碼

public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {  

  public Resource getResource(String location) {  

    //這里調用當前的loader也就是DefaultResourceLoader來(lái)完成載入  

    if (this.resourceLoader != null) {  

      return this.resourceLoader.getResource(location);  

    }  

    return super.getResource(location);  

  }  

.......  

} 

  而我們的FileSystemXmlApplicationContext就是一個(gè)DefaultResourceLoader - GenericApplicationContext()通過(guò)DefaultResourceLoader:

  代碼

public Resource getResource(String location) {  

  //如果是類(lèi)路徑的方式,那需要使用ClassPathResource來(lái)得到bean文件的資源對象  

  if (location.startsWith(CLASSPATH_URL_PREFIX)) {  

    return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());  

  }  

  else {  

    try {  

      // 如果是URL方式,使用UrlResource作為bean文件的資源對象  

      URL url = new URL(location);  

      return new UrlResource(url);  

    }  

    catch (MalformedURLException ex) {  

      // 如果都不是,那我們只能委托給子類(lèi)由子類(lèi)來(lái)決定使用什么樣的資源對象了  

      return getResourceByPath(location);  

    }  

  }  

}

我們的FileSystemXmlApplicationContext本身就是是DefaultResourceLoader的實(shí)現類(lèi),他實(shí)現了以下的接口:

  代碼

protected Resource getResourceByPath(String path) {  

  if (path != null && path.startsWith("/")) {  

    path = path.substring(1);  

  }  

  //這里使用文件系統資源對象來(lái)定義bean文件  

  return new FileSystemResource(path);  

} 

  這樣代碼就回到了FileSystemXmlApplicationContext中來(lái),他提供了FileSystemResource來(lái)完成從文件系統得到配置文件的資源定義。這樣,就可以從文件系統路徑上對IOC配置文件進(jìn)行加載 - 當然我們可以按照這個(gè)邏輯從任何地方加載,在Spring中我們看到它提供的各種資源抽象,比如ClassPathResource, URLResource,FileSystemResource等來(lái)供我們使用。上面我們看到的是定位Resource的一個(gè)過(guò)程,而這只是加載過(guò)程的一部分 - 我們回到AbstractBeanDefinitionReaderz中的loadDefinitions(resource)來(lái)看看得到代表bean文件的資源定義以后的載入過(guò)程,默認的我們使用XmlBeanDefinitionReader:

  代碼

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {  

  .......  

  try {  

    //這里通過(guò)Resource得到InputStream的IO流  

    InputStream inputStream = encodedResource.getResource().getInputStream();  

    try {  

      //從InputStream中得到XML的解析源  

      InputSource inputSource = new InputSource(inputStream);  

      if (encodedResource.getEncoding() != null) {  

        inputSource.setEncoding(encodedResource.getEncoding());  

      }  

      //這里是具體的解析和注冊過(guò)程  

      return doLoadBeanDefinitions(inputSource, encodedResource.getResource());  

    }  

    finally {  

      //關(guān)閉從Resource中得到的IO流  

      inputStream.close();  

    }  

  }  

    .........  

}  

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)  

    throws BeanDefinitionStoreException {  

  try {  

    int validationMode = getValidationModeForResource(resource);  

    //通過(guò)解析得到DOM,然后完成bean在IOC容器中的注冊  

    Document doc = this.documentLoader.loadDocument(  

        inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);  

    return registerBeanDefinitions(doc, resource);  

  }  

.......  

}

我們看到先把定義文件解析為DOM對象,然后進(jìn)行具體的注冊過(guò)程:

  代碼

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {  

  // 這里定義解析器,使用XmlBeanDefinitionParser來(lái)解析xml方式的bean定義文件 - 現在的版本不用這個(gè)解析器了,使用的是XmlBeanDefinitionReader  

  if (this.parserClass != null) {  

    XmlBeanDefinitionParser parser =  

        (XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass);  

    return parser.registerBeanDefinitions(this, doc, resource);  

  }  

  // 具體的注冊過(guò)程,首先得到XmlBeanDefinitionReader,來(lái)處理xml的bean定義文件  

  BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();  

  int countBefore = getBeanFactory().getBeanDefinitionCount();  

  documentReader.registerBeanDefinitions(doc, createReaderContext(resource));  

  return getBeanFactory().getBeanDefinitionCount() - countBefore;  

} 

  具體的在BeanDefinitionDocumentReader中完成對,下面是一個(gè)簡(jiǎn)要的注冊過(guò)程來(lái)完成bean定義文件的解析和IOC容器中bean的初始化

  代碼

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {  

  this.readerContext = readerContext;  

  logger.debug("Loading bean definitions");  

  Element root = doc.getDocumentElement();  

  BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);  

  preProcessXml(root);  

  parseBeanDefinitions(root, delegate);  

  postProcessXml(root);  

}  

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {  

  if (delegate.isDefaultNamespace(root.getNamespaceURI())) {  

    //這里得到xml文件的子節點(diǎn),比如各個(gè)bean節點(diǎn)      

    NodeList nl = root.getChildNodes();  

    //這里對每個(gè)節點(diǎn)進(jìn)行分析處理  

    for (int i = 0; i < nl.getLength(); i++) {  

      Node node = nl.item(i);  

      if (node instanceof Element) {  

        Element ele = (Element) node;  

        String namespaceUri = ele.getNamespaceURI();  

        if (delegate.isDefaultNamespace(namespaceUri)) {  

          //這里是解析過(guò)程的調用,對缺省的元素進(jìn)行分析比如bean元素  

          parseDefaultElement(ele, delegate);  

        }  

        else {  

          delegate.parseCustomElement(ele);  

        }  

      }  

    }  

  } else {  

    delegate.parseCustomElement(root);  

  }  

}  

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {  

  //這里對元素Import進(jìn)行處理  

  if (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) {  

    importBeanDefinitionResource(ele);  

  }  

  else if (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) {  

    String name = ele.getAttribute(NAME_ATTRIBUTE);  

    String alias = ele.getAttribute(ALIAS_ATTRIBUTE);  

    getReaderContext().getReader().getBeanFactory().registerAlias(name, alias);  

    getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));  

  }  

  //這里對我們最熟悉的bean元素進(jìn)行處理  

  else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) {  

    //委托給BeanDefinitionParserDelegate來(lái)完成對bean元素的處理,這個(gè)類(lèi)包含了具體的bean解析的過(guò)程?! ?/p>

    // 把解析bean文件得到的信息放到BeanDefinition里,他是bean信息的主要載體,也是IOC容器的管理對象?! ?/p>

    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);  

    if (bdHolder != null) {  

      bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);  

      // 這里是向IOC容器注冊,實(shí)際上是放到IOC容器的一個(gè)map里  

      BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());  

      // 這里向IOC容器發(fā)送事件,表示解析和注冊完成?! ?/p>

      getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));  

    }  

  }  

} 

我們看到在parseBeanDefinition中對具體bean元素的解析式交給BeanDefinitionParserDelegate來(lái)完成的,下面我們看看解析完的bean是怎樣在IOC容器中注冊的:

  在BeanDefinitionReaderUtils調用的是:

  代碼

public static void registerBeanDefinition(  

    BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory) throws BeansException {  

  // 這里得到需要注冊bean的名字;  

  String beanName = bdHolder.getBeanName();  

  //這是調用IOC來(lái)注冊的bean的過(guò)程,需要得到BeanDefinition  

  beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());  

  // 別名也是可以通過(guò)IOC容器和bean聯(lián)系起來(lái)的進(jìn)行注冊  

  String[] aliases = bdHolder.getAliases();  

  if (aliases != null) {  

    for (int i = 0; i < aliases.length; i++) {  

      beanFactory.registerAlias(beanName, aliases[i]);  

    }  

  }  

}

  我們看看XmlBeanFactory中的注冊實(shí)現:

  代碼

//---------------------------------------------------------------------  

// 這里是IOC容器對BeanDefinitionRegistry接口的實(shí)現  

//---------------------------------------------------------------------  

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)  

    throws BeanDefinitionStoreException {  

  .....//這里省略了對BeanDefinition的驗證過(guò)程  

  //先看看在容器里是不是已經(jīng)有了同名的bean,如果有拋出異常?! ?/p>

  Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);  

  if (oldBeanDefinition != null) {  

    if (!this.allowBeanDefinitionOverriding) {  

    ...........  

  }  

  else {  

    //把bean的名字加到IOC容器中去  

    this.beanDefinitionNames.add(beanName);  

  }  

  //這里把bean的名字和Bean定義聯(lián)系起來(lái)放到一個(gè)HashMap中去,IOC容器通過(guò)這個(gè)Map來(lái)維護容器里的Bean定義信息?! ?/p>

  this.beanDefinitionMap.put(beanName, beanDefinition);  

  removeSingleton(beanName);  

}

這樣就完成了Bean定義在IOC容器中的注冊,就可被IOC容器進(jìn)行管理和使用了。

  從上面的代碼來(lái)看,我們總結一下IOC容器初始化的基本步驟:

  * 初始化的入口在容器實(shí)現中的refresh()調用來(lái)完成

  * 對bean 定義載入IOC容器使用的方法是loadBeanDefinition,其中的大致過(guò)程如下:通過(guò)ResourceLoader來(lái)完成資源文件位置的定位,DefaultResourceLoader是默認的實(shí)現,同時(shí)上下文本身就給出了ResourceLoader的實(shí)現,可以從類(lèi)路徑,文件系統, URL等方式來(lái)定為資源位置。如果是XmlBeanFactory作為IOC容器,那么需要為它指定bean定義的資源,也就是說(shuō)bean定義文件時(shí)通過(guò)抽象成Resource來(lái)被IOC容器處理的,容器通過(guò)BeanDefinitionReader來(lái)完成定義信息的解析和Bean信息的注冊,往往使用的是XmlBeanDefinitionReader來(lái)解析bean的xml定義文件 - 實(shí)際的處理過(guò)程是委托給BeanDefinitionParserDelegate來(lái)完成的,從而得到bean的定義信息,這些信息在Spring中使用BeanDefinition對象來(lái)表示 - 這個(gè)名字可以讓我們想到loadBeanDefinition,RegisterBeanDefinition這些相關(guān)的方法 - 他們都是為處理BeanDefinitin服務(wù)的,IoC容器解析得到BeanDefinition以后,需要把它在IOC容器中注冊,這由IOC實(shí)現 BeanDefinitionRegistry接口來(lái)實(shí)現。注冊過(guò)程就是在IOC容器內部維護的一個(gè)HashMap來(lái)保存得到的 BeanDefinition的過(guò)程。這個(gè)HashMap是IoC容器持有bean信息的場(chǎng)所,以后對bean的操作都是圍繞這個(gè)HashMap來(lái)實(shí)現的。

  * 然后我們就可以通過(guò)BeanFactory和ApplicationContext來(lái)享受到Spring IOC的服務(wù)了.

  在使用IOC容器的時(shí)候,我們注意到除了少量粘合代碼,絕大多數以正確IoC風(fēng)格編寫(xiě)的應用程序代碼完全不用關(guān)心如何到達工廠(chǎng),因為容器將把這些對象與容器管理的其他對象鉤在一起?;镜牟呗允前压S(chǎng)放到已知的地方,最好是放在對預期使用的上下文有意義的地方,以及代碼將實(shí)際需要訪(fǎng)問(wèn)工廠(chǎng)的地方。 Spring本身提供了對聲明式載入web應用程序用法的應用程序上下文,并將其存儲在ServletContext中的框架實(shí)現。具體可以參見(jiàn)以后的文章。

在使用Spring IOC容器的時(shí)候我們還需要區別兩個(gè)概念:

  Beanfactory 和Factory bean,其中BeanFactory指的是IOC容器的編程抽象,比如ApplicationContext, XmlBeanFactory等,這些都是IOC容器的具體表現,需要使用什么樣的容器由客戶(hù)決定但Spring為我們提供了豐富的選擇。而 FactoryBean只是一個(gè)可以在IOC容器中被管理的一個(gè)bean,是對各種處理過(guò)程和資源使用的抽象,Factory bean在需要時(shí)產(chǎn)生另一個(gè)對象,而不返回FactoryBean本省,我們可以把它看成是一個(gè)抽象工廠(chǎng),對它的調用返回的是工廠(chǎng)生產(chǎn)的產(chǎn)品。所有的 Factory bean都實(shí)現特殊的org.springframework.beans.factory.FactoryBean接口,當使用容器中factory bean的時(shí)候,該容器不會(huì )返回factory bean本身,而是返回其生成的對象。Spring包括了大部分的通用資源和服務(wù)訪(fǎng)問(wèn)抽象的Factory bean的實(shí)現,其中包括:

  對JNDI查詢(xún)的處理,對代理對象的處理,對事務(wù)性代理的處理,對RMI代理的處理等,這些我們都可以看成是具體的工廠(chǎng),看成是SPRING為我們建立好的工廠(chǎng)。也就是說(shuō)Spring通過(guò)使用抽象工廠(chǎng)模式為我們準備了一系列工廠(chǎng)來(lái)生產(chǎn)一些特定的對象,免除我們手工重復的工作,我們要使用時(shí)只需要在IOC容器里配置好就能很方便的使用了。

  現在我們來(lái)看看在Spring的事件機制,Spring中有3個(gè)標準事件,ContextRefreshEvent, ContextCloseEvent,RequestHandledEvent他們通過(guò)ApplicationEvent接口,同樣的如果需要自定義時(shí)間也只需要實(shí)現ApplicationEvent接口,參照ContextCloseEvent的實(shí)現可以定制自己的事件實(shí)現:

  代碼

public class ContextClosedEvent extends ApplicationEvent {  

  public ContextClosedEvent(ApplicationContext source) {  

    super(source);  

  }  

  public ApplicationContext getApplicationContext() {  

    return (ApplicationContext) getSource();  

  }  

} 

可以通過(guò)顯現ApplicationEventPublishAware接口,將事件發(fā)布器耦合到ApplicationContext這樣可以使用 ApplicationContext框架來(lái)傳遞和消費消息,然后在A(yíng)pplicationContext中配置好bean就可以了,在消費消息的過(guò)程中,接受者通過(guò)實(shí)現ApplicationListener接收消息。

  比如可以直接使用Spring的ScheduleTimerTask和TimerFactoryBean作為定時(shí)器定時(shí)產(chǎn)生消息,具體可以參見(jiàn)《Spring框架高級編程》。

  TimerFactoryBean是一個(gè)工廠(chǎng)bean,對其中的ScheduleTimerTask進(jìn)行處理后輸出,參考ScheduleTimerTask的實(shí)現發(fā)現它最后調用的是jre的TimerTask:

  Java代碼

  public void setRunnable(Runnable timerTask) {

    this.timerTask = new DelegatingTimerTask(timerTask);

  }

  在書(shū)中給出了一個(gè)定時(shí)發(fā)送消息的例子,當然可以可以通過(guò)定時(shí)器作其他的動(dòng)作,有兩種方法:

  1.定義MethodInvokingTimerTaskFactoryBean定義要執行的特定bean的特定方法,對需要做什么進(jìn)行封裝定義;

  2.定義TimerTask類(lèi),通過(guò)extends TimerTask來(lái)得到,同時(shí)對需要做什么進(jìn)行自定義

  然后需要定義具體的定時(shí)器參數,通過(guò)配置ScheduledTimerTask中的參數和timerTask來(lái)完成,以下是它需要定義的具體屬性,timerTask是在前面已經(jīng)定義好的bean

  Java代碼

  private TimerTask timerTask;

  private long delay = 0;

  private long period = 0;

  private boolean fixedRate = false;

  最后,需要在A(yíng)pplicationContext中注冊,需要把ScheduledTimerTask配置到FactoryBean - TimerFactoryBean,這樣就由IOC容器來(lái)管理定時(shí)器了。參照

  TimerFactoryBean的屬性,可以定制一組定時(shí)器。

  Java代碼

public class TimerFactoryBean implements FactoryBean, InitializingBean, DisposableBean {

  protected final Log logger = LogFactory.getLog(getClass());

  private ScheduledTimerTask[] scheduledTimerTasks;

  private boolean daemon = false;

  private Timer timer;

  ...........

}

  如果要發(fā)送時(shí)間我們只需要在定義好的ScheduledTimerTasks中publish定義好的事件就可以了。具體可以參考書(shū)中例子的實(shí)現,這里只是結合FactoryBean的原理做一些解釋。如果結合事件和定時(shí)器機制,我們可以很方便的實(shí)現heartbeat(看門(mén)狗),書(shū)中給出了這個(gè)例子,這個(gè)例子實(shí)際上結合了Spring事件和定時(shí)機制的使用兩個(gè)方面的知識 - 當然了還有IOC容器的知識(任何Spring應用我想都逃不掉IOC的魔爪:

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
讀《Spring
『互聯(lián)網(wǎng)架構』軟件架構
spring的面試題
《Spring3.X企業(yè)應用開(kāi)發(fā)實(shí)戰》學(xué)習筆記
Spring IoC 詳解(四)
【初探Spring】Spring IOC(二):初始化過(guò)程---簡(jiǎn)介
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久