JDK8 函数试编程使用例子

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);
}

这里,然后将结果放回到

1635ad250534edf543d0d3cdd126da58dd2.jpg

这样就可以继续往下执行。

转载于:https://my.oschina.net/u/1169535/blog/3057523

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值