JDK8 新增特性,函数式编程,一般可以通过配合lambda表达式使用,下面举一个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这个方法执行到
try { singletonObject = singletonFactory.getObject(); newSingleton = true; }
这行代码的时候首先会执行外围方法:
try { return createBean(beanName, mbd, args); }
这里,然后将结果放回到
这样就可以继续往下执行。