网站首页 > 技术文章 正文
在本期文章中,我们将介绍Java 14中的新特性及其在构建基于SpringBoot的应用程序中的应用。
开始,我们需要使用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
财产:
<properties>
<java.version>14</java.version>
</properties>
这允许我们的构建使用Java 14和该版本中所有发布的特性,但是要真正体验Java 14的新奇之处,我们需要打开预览功能-发行版中提供的但默认情况下不活动的特性。
在
<plugins>...</plugins>
节,添加以下插件配置,以启用Java 14的预览功能。
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>14</release>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
现在你可以走了!让我们看看一些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<Person> 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<ApplicationReadyEvent
:
@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就业大礼包。
线上视频、音频,随时学习观看
关注我们并私信“资料”即可获取。
- 上一篇: Nginx常见问题
- 下一篇: 使用ANTLR开发自己的DSL语言(一)
猜你喜欢
- 2025-05-26 学习HackerOne上Flink、Grafana、jolokia攻击手法
- 2025-05-26 使用ANTLR开发自己的DSL语言(一)
- 2025-05-26 Nginx常见问题
- 2025-05-26 MyBatis系列-2-日志配置
- 2025-05-26 免费且好用的乐谱制作软件
- 2025-05-26 进阶版Python正则表达式大全,看到就赚到了
- 2025-05-26 让你把DeepSeek不借助插件装进WPS中 WPS接入DeepSeek人工智能
- 2025-05-26 在word中通过VBA调用百度翻译API在线翻译
- 2025-05-26 Java文件读取终极指南:4种方式对比与性能优化实战
- 2025-05-26 Groovy和Java
- 最近发表
-
- 使用这个新的 ECMAScript 运算符告别 Try/Catch!
- 抛弃 try-catch,错误处理的新方案
- 深圳尚学堂Java培训:总结java编程常用的快捷键(二)
- Try-catch speeding up my code?(speeding up)
- 能代替try catch处理异常的优雅方式
- Linux系统stress压力测试工具(linux自带的压力测试)
- ESL-通过事件控制FreeSWITCH(es事务控制)
- 谈JVM xmx, xms等内存相关参数合理性设置
- 嵌入式工程师竟然看不懂这些专业语句,那真别怪人说你菜
- 不会前端也能写官网?没问题,Devbox+Cursor 带你起飞
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)