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