JDK1.8 Lambda 及 springboot 源码中运用的一个小场景

今天是裸辞整整2周,感觉慢慢开始习惯了,没有短信轰炸,没有企业微信推送,没有代办事项...

JDK1.8对应的新特性比较多了,主要有lambda表达式支持、方法引用、Stream API以及JVM内存模型的一些调整。这里主要学习一下lambda 以及方法引用。

Lambda

Lambda 表达式就像三元表达式一样,是一种连贯的将逻辑进行表达的方式,Lambda的语法建立在函数式接口 FunctionInterface 的基础上,书写Lambda表达式时我们需要先定一个函数式接口interface,然后对interface的抽象方法使用Lambda表达式进行实现。

    @FunctionalInterface
    interface LambdaTest {
        void test();
    }

    public static void main(String[] args) {
        LambdaTest lambdaTest = ()-> System.out.println("empty method");
        lambdaTest.test();
    }

刚开始接触Lambda看到上面的第一感觉是有点懵逼的,表达式中没有出现test()方法的实现关键字,这就是Lambda的魔力所在,感觉参数自动映射到对应的方法,不过魔力也只是表象,真正的原因是FunctionalInterface 定义的接口只能有且只有一个待实现的抽象方法,那不映射它还能映射谁呢,所以直接省略掉名字。

这也是我看springboot源码有关ApplicationContextFactory接口时没有反映过来,拼命到处找抽象方法create的实现无果的原因,后面会引用这个来说明下Lambda在springboot 源码中的应用。

Lambda 语法

(parameters) -> expression
或
(parameters) ->{ statements; }

括号内的parameters 和FunctionalInterface中定义的方法一样,空、单个参数、多个参数都可以,expression 标示单个逻辑实现,单行单句的情况,如果是多行多句就需要使用{}括号起来。
【注意】expresion语句即使有返回值,也可以省略return 关键字
下面列举的是几个参数以及返回值接口定义及其Lambda表达式实现的

    //带一个参数
    @FunctionalInterface
    interface LambdaTest2 {
        void test(String s);
    }
    public static void main(String[] args) {
        LambdaTest2 lambdaTest2 = (x)-> System.out.println(x);
        lambdaTest2.test("abc");
    }
    //输出:abc

   
    //带2个参数
    @FunctionalInterface
    interface LambdaTest3 {
        void test(String s,String a);
    }
    public static void main(String[] args) {
        LambdaTest3 lambdaTest3 = (x,y) -> System.out.println(x+y);
        lambdaTest3.test("x","y");
    }
    //输出:xy

    //带2个参数,1个返回值
    @FunctionalInterface
    interface LambdaTest4 {
        String test(String s,String a);
    }
    public static void main(String[] args) {
        LambdaTest4 lambdaTest4 = (x,y) -> x+"_"+y;
        System.out.println(lambdaTest4.test("a","b"));
    }
    //输出:a_b

Lambda在springboot SpringApplication.class 中的应用

相信你也有去了解过SpringApplication.run方法里面都执行了什么操作,如果没有看过,可以花点时间了解下,还是可以学习到不少东西,更好的使用springboot

在SpringApplication(springboot 2.4.5)构造方法是下面这样

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        this.sources = new LinkedHashSet();
        this.bannerMode = Mode.CONSOLE;
        this.logStartupInfo = true;
        this.addCommandLineProperties = true;
        this.addConversionService = true;
        this.headless = true;
        this.registerShutdownHook = true;
        this.additionalProfiles = Collections.emptySet();
        this.isCustomEnvironment = false;
        this.lazyInitialization = false;
        this.applicationContextFactory = ApplicationContextFactory.DEFAULT;
        this.applicationStartup = ApplicationStartup.DEFAULT;
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        this.bootstrapRegistryInitializers = this.getBootstrapRegistryInitializersFromSpringFactories();
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

其中下面这2行代码是我们要说明的重点

//springboot会根据加载的类来判断当前是什么类型的项目,    NONE,SERVLET,REACTIVE 三者中之一
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//这里就是引用了一个Lambda表达式
//这个表达式的内容写在了对应的函数式接口中而已
this.applicationContextFactory = ApplicationContextFactory.DEFAULT;

对应的函数式接口ApplicationContextFactory代码如下:

@FunctionalInterface
public interface ApplicationContextFactory {
    ApplicationContextFactory DEFAULT = (webApplicationType) -> {
        try {
            switch(webApplicationType) {
            case SERVLET:
                return new AnnotationConfigServletWebServerApplicationContext();
            case REACTIVE:
                return new AnnotationConfigReactiveWebServerApplicationContext();
            default:
                return new AnnotationConfigApplicationContext();
            }
        } catch (Exception var2) {
            throw new IllegalStateException("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2);
        }
    };

    ConfigurableApplicationContext create(WebApplicationType webApplicationType);
}

上面DEFAULT 这里是一个LAMBDA表达式,实现的是下面 create方法,返回的是一个ConfigurableApplicationContext 实现类。

上面提到的我到处去找create方法的实现,没想到实现就在上面,“众里寻他千百度,蓦然回首,那人却在,灯火阑珊处”。

方法引用

第一眼看到java代码中如下面样式的代码的时候,还以为这个应该不是java代码吧,应该是C#之类的。

 NameInterface nameInterface = Person::getName

上面这个就是JDK1.8新特性:方法引用。
定义:方法引用通过方法的名字来指向一个方法,可以使语言的构造更紧凑简洁,减少冗余代码。
作用:当我们定义了一个接口抽象方法,然后发现其他地方有你想要的实现逻辑方法,那就不用再费力去写一个,即使这个实现方法和当前模块没有任何关系,引用过来用就是了。这就是方法引用,将某一目标方法代码复制过来使用。

下面是一个列子:

@FunctionalInterface
interface MethodTest{
    void print(String name);
}
//和MethodTest没有任何关系的类一个
class Person2{
    private String name;

    public Person2(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void print(String name){
        System.out.println("name="+name);
    }
}

public static void main(String[] args) {
        MethodTest methodTest = new Person2("abc")::print;
        methodTest.print("method test print");
    }

//输出:name=method test print

就是这么神奇。上面MethodTest定义的抽象方法名字同Person中国呢定义的方法print并不一定要相同名字,只要返回参数以及输入参数等签名一致即可。

说在最后

Lambda 的作用,将实现函数逻辑部分的代码,用表达式的形式定义到一个变量中,然后将变量作为方法入参传到方法中。
方法引用的作用:复用其他代码,减少冗余代码。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容