spring boot 预览图片_Spring技巧:深入研究Java 14和SpringBoot

在本期文章中,我们将介绍Java 14中的新特性及其在构建基于SpringBoot的应用程序中的应用。

943faf913077070c5127ebb42b80399c.png

​开始,我们需要使用Java的最新版本,也是最棒的版本,Java 14,它现在还没有发布。预计将于2020年初发运。上下载早期访问版本。Java.net。您也可以考虑使用SDKManager(

sdk

),这使得安装新JVM版本确实是一件小事。

记住,每6个月就有新的Java版本。这些新版本可以在生产中使用,但只支持一个版本和下一个版本之间的六个月。Java项目不时也会发布一个长期支持(LTS)版本。目前的版本是Java 11,Java 14在Java 15发布之前只是一个可行的生产目标。事实上,我们要研究的是预览功能,人们可能会说,这根本不应该在生产中。你被警告了!

如果使用SDKManager,可以运行以下咒语来安装Java 14。

sdk install java 14.ea.36-open

去Spring Initializr并使用SpringBoot2.3或更高版本生成一个新项目。您还需要选择

JDBC

PostgreSQL

.

SpringBoot的旧版本还不支持Java 14运行时。当然,为了编辑这个版本的Java,您需要将它导入到IDE中。不过,在您这样做之前,让我们修改一下

pom.xml

要将构建配置为支持Java 14,通常,当您转到SpringInitializr时,您还指定了Java的一个版本。目前还不支持Java 14,因此我们希望手动配置一些东西。

通过更改

java.version

财产:

14

这允许我们的构建使用Java 14和该版本中所有发布的特性,但是要真正体验Java 14的新奇之处,我们需要打开预览功能-发行版中提供的但默认情况下不活动的特性。

...

节,添加以下插件配置,以启用Java 14的预览功能。

maven-compiler-plugin

14

--enable-preview

true

true

maven-surefire-plugin

--enable-preview

现在你可以走了!让我们看看一些Java代码。SpringInitializr为我们提供了一个项目和一个基本入口点类:

package com.example.fourteen;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.context.event.ApplicationReadyEvent;

import org.springframework.context.event.EventListener;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.PreparedStatementCreatorFactory;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.jdbc.core.SqlParameter;

import org.springframework.jdbc.support.GeneratedKeyHolder;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Service;

import java.sql.Types;

import java.util.List;

@SpringBootApplication

public class FourteenApplication {

public static void main(String[] args) {

SpringApplication.run(FourteenApplication.class, args);

}

}

我们将创建一个简单的JDBC驱动服务,它使用SQL将其数据写入数据库。我们需要一个映射到数据库表中数据的对象

people

.

此时,我通常要么使用IDE的代码生成工具来编写Javabean对象,要么使用Lombok来注释我的方式到具有geters、setter的编译器合成的对象,

toString

的实现

equals

。我甚至可能会勉强引用其他语言的能力,使这种乏味的工作变得琐碎。Scala支持案例类。科特林支持数据类.

Java 14支持_Record_s。

record Person(Integer id, String name, int emotionalState) {

}

还不错吧?这个语法包了一个Wallop!它提供了一个具有构造函数和构造函数参数、属性、实现的新对象。

equals

toString

还有更多。我们可以像其他对象一样实例化这个对象的实例。尝试取消对象中的引用属性,那么我们的构造函数属性就会变成

id()

/

id(int)

,

name()

/

name(String)

,和

emotionalState()

/

emotionalState(int)

。对这么小的人来说还不错!

让我们看一下

PeopleService

.

这个

PeopleService

使用

JdbcTemplate

将数据库查询的结果转换为Java对象的简短工作。如果您曾经使用过

JdbcTemplate

(谁没有)?我留下了一些未实现的部分,这样我们就可以直接重新讨论这些部分了。

@Service

class PeopleService {

private final JdbcTemplate template;

//todo

private final String findByIdSql = null;

private final String insertSql = null;

private final RowMapper personRowMapper =

(rs, rowNum) -> new Person(rs.getInt("id"), rs.getString("name"), rs.getInt("emotional_state"));

PeopleService(JdbcTemplate template) {

this.template = template;

}

public Person create(String name, EmotionalState state) {

//todo

}

public Person findById(Integer id) {

return this.template.queryForObject(this.findByIdSql, new Object[]{id}, this.personRowMapper);

}

}

首先,我们将使用一些SQL查询。在我的生活中,为了避免在Java代码中键入SQL查询,我付出了很大的代价。我的天啊,如果人们知道自己能用Java来表达SQL查询,他们会经常使用ORM吗?

Strings

?对于任何稍微复杂的内容,我都会将SQL查询提取到属性文件中,然后用Spring的配置属性机制加载这些文件。

但是,我们可以在Java 14中做得更好!多行字符串终于出现在Java上了!它现在加入了Python、Ruby、C++、C#、Rust、PHP、Kotlin、Scala、Groovy、Go、JavaScript、Clojure以及其他十几种语言的行列。我很高兴它终于来了!

替换

sql

具有以下声明的变量。

private final String findByIdSql =

"""

select * from PEOPLE

where ID = ?

""";

private final String insertSql =

"""

insert into PEOPLE(name, emotional_state)

values (?,?);

""";

太好了,那个!有一些方法可以用来修剪边距等等。还可以使用反斜杠转义序列(

)在每一行的末尾,指示下一行应该从那里开始,否则换行符就会被逐字解释。

让我们看看

create

方法。

存储

Person

emotionalState

在数据库中作为

int

是实现细节。我不想让用户有这种想法。让我们用一个枚举来描述每个人的情绪状态

Person

:

enum EmotionalState {

SAD, HAPPY, NEUTRAL

}

我想这是个开始。让我们来讨论实现。我们马上就有机会在Java 14中使用另一个很好的新特性:智能开关表达式。Switch表达式为我们提供了一种从开关大小写的分支返回值的方法,然后将其赋值给变量。语法是差不多了和我们以前用过的一样,只是每个箱子都是用箭头从树枝上射出的,->,不是:,没有必要break声明。

在下面的示例中,我们分配int变量的值index,我们不需要指定它的类型,因为最近Java迭代中的另一个很好的特性是自动类型推断var.

public Person create(String name, EmotionalState state) {

var index = switch (state) {

case SAD -> -1;

case HAPPY -> 1;

case NEUTRAL -> 0;

};

// todo

}

带着

index

在手,我们可以创造必要的

PreparedStatement

需要对数据库执行SQL语句。我们可以执行准备好的语句并传入一个

KeyHolder

它将用于收集从新插入的行返回的生成密钥。

public Person create(String name, EmotionalState state) {

var index = switch (state) {

case SAD -> -1;

case HAPPY -> 1;

case NEUTRAL -> 0;

};

var declaredParameters = List.of(

new SqlParameter(Types.VARCHAR, "name"),

new SqlParameter(Types.INTEGER, "emotional_state"));

var pscf = new PreparedStatementCreatorFactory(this.insertSql, declaredParameters) {

{

setReturnGeneratedKeys(true);

setGeneratedKeysColumnNames("id");

}

};

var psc = pscf.newPreparedStatementCreator(List.of(name, index));

var kh = new GeneratedKeyHolder();

this.template.update(psc, kh);

// todo

}

唯一的问题是返回的密钥是

Number

,而不是

Integer

或者是

Double

或者任何更具体的东西。这让我们有机会在Java 14中使用另一个有趣的新特性,即智能转换。智能转换允许我们在测试

instanceof

测试一下。它更进一步,给出了一个变量名,通过它我们可以引用测试范围中的自动强制转换变量。

public Person create(String name, EmotionalState state) {

var index = switch (state) {

case SAD -> -1;

case HAPPY -> 1;

case NEUTRAL -> 0;

};

var declaredParameters = List.of(

new SqlParameter(Types.VARCHAR, "name"),

new SqlParameter(Types.INTEGER, "emotional_state"));

var pscf = new PreparedStatementCreatorFactory(this.insertSql, declaredParameters) {

{

setReturnGeneratedKeys(true);

setGeneratedKeysColumnNames("id");

}

};

var psc = pscf.newPreparedStatementCreator(List.of(name, index));

var kh = new GeneratedKeyHolder();

this.template.update(psc, kh);

if (kh.getKey() instanceof Integer id) {

return findById(id);

}

throw new IllegalArgumentException("we couldn't create the " + Person.class.getName() + "!");

}

我们需要一个

int

才能把它传递给

findById(Integer)

这种方法对我们来说是可行的。方便,嗯?

一切正常,所以让我们用一个简单的

ApplicationListener

:

@Component

class Runner {

private final PeopleService peopleService;

Runner(PeopleService peopleService) {

this.peopleService = peopleService;

}

@EventListener(ApplicationReadyEvent.class)

public void exercise() throws Exception {

var elizabeth = this.peopleService.create("Elizabeth", EmotionalState.SAD);

System.out.println(elizabeth);

}

}

运行它,您将看到对象已经写入数据库,而且--最好的是--您得到了一个漂亮的新

toString()

打印结果时的结果。

Person

反对!

我们刚刚开始触及Java 14中所有新特性的表面!在这个视频中,我们已经开始在语言中引入了大量的新特性,并且在运行时本身有更多的安全性和性能特性。我非常诚恳地建议您找到摆脱JDK旧版本的方法(看看您,Java 8用户!)转移到最新的。


为感谢您对我们的认可,特意准备了一些IT入门和进阶的干货

包括:Java、UI设计、H5前端、Python+人工智能、软件测试和新媒体运营六大学科视频资料。以及IT就业大礼包。

线上视频、音频,随时学习观看

关注我们并私信“资料”即可获取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值