JDK8 函數試編程使用例子

JDK8 新增特性,函數式編程,通常能夠經過配合lambda表達式使用,下面舉一個spring中使用函數式編程的例子spring

1,spring在實例化類的時候使用到了lambda表達式,首先它定義了一個函數式接口編程

@FunctionalInterface
public interface ObjectFactory<T> {

   /**
    * Return an instance (possibly shared or independent)
    * of the object managed by this factory.
    * @return the resulting instance
    * @throws BeansException in case of creation errors
    */
   T getObject() throws BeansException;

}

2,接着在org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean中使用到了,看一下具體代碼函數式編程

if (mbd.isSingleton()) {
   sharedInstance = getSingleton(beanName, () -> {
      try {
         return createBean(beanName, mbd, args);
      }
      catch (BeansException ex) {
         // Explicitly remove instance from singleton cache: It might have been put there
         // eagerly by the creation process, to allow for circular reference resolution.
         // Also remove any beans that received a temporary reference to the bean.
         destroySingleton(beanName);
         throw ex;
      }
   });
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

你們必定發現了,這段代碼跟那個函數式接口也沒有半毛錢關係啊?你們能夠點擊getSingleton這個方法進去看一下具體參數:函數

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
   Assert.notNull(beanName, "Bean name must not be null");
   synchronized (this.singletonObjects) {
      Object singletonObject = this.singletonObjects.get(beanName);
      if (singletonObject == null) {
         if (this.singletonsCurrentlyInDestruction) {
            throw new BeanCreationNotAllowedException(beanName,
                  "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                  "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
         }

沒錯,第二個參數就是那個函數式接口,可是爲何就只變成了一個方法體了呢?這就是函數式變成的使用方式,當getSingleton這個方法執行到this

try {
   singletonObject = singletonFactory.getObject();
   newSingleton = true;
}

這行代碼的時候首先會執行外圍方法:blog

try {
   return createBean(beanName, mbd, args);
}

這裏,而後將結果放回到接口

這樣就能夠繼續往下執行。ci

相關文章
相關標籤/搜索