日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
SpringBoot2.6新特性:使用Java17的Record作為配置屬性

Spring Boot 3.0的基線版本是Java 17,Spring Boot 3.0版本將全面對Java 17的支持。較新版本的2.x的Spring Boot版本也可以使用Java 17的特性。

本文介紹Spring Boot 2.6對Java 17支持的一個(gè)新特性,使用Java 17的Record來做為Spring Boot的配置屬性(ConfiguartionProperties)。

什么是Record

record是一種特殊類型的類聲明,目的是為了減少樣板代碼。record引入的主要目的是快速創(chuàng)建數(shù)據(jù)載體類。

這種類的主要目的就是在不同的模塊或者層之間包含并傳遞數(shù)據(jù),它們表現(xiàn)為POJO(Plain Old Java Objects)和DTO(Data Transfer Objects)。

record聲明有專門的的關(guān)鍵字record,我們比較下一個(gè)簡單的POJO類和record上語法的區(qū)別:

POJO類:

@Data
public class Point {
private String x;
private String y;
}

record:

public record Point(String x, String y) {
}

Spring Boot的配置屬性(Configuration Properties)類也是一個(gè)簡單POJO。

用POJO類作為Configuration Properties

新建演示項(xiàng)目,注意添加Spring Configuration Processor

演示的Configuration Properties,首先我們使用常規(guī)的Java類來演示

@ConfigurationProperties(prefix = "author")
@Data
public class AuthorProperties {
private String firstName;
private String lastName;
}
  • application.properties中的配置
author.firstName=wang
author.lastName=yunfei
  • 注冊Configuration Properties為Bean,并使用
@SpringBootApplication
@EnableConfigurationProperties(AuthorProperties.class)//將AuthorProperties注冊為Bean
@Slf4j
public class RecordConfigurationPropertiesApplication {

public static void main(String[] args) {
SpringApplication.run(RecordConfigurationPropertiesApplication.class, args);
}

@Bean //注入并使用AuthorProperties的Bean
CommandLineRunner commandLineRunner(AuthorProperties authorProperties){
return args -> {
log.info(authorProperties.toString());
};
}
}
  • 運(yùn)行程序

用Record作為Configuration Properties

我們只需要將AuthorProperties類修改為record即可:

@ConfigurationProperties(prefix = "author")
public record AuthorProperties(String firstName, String lastName) {
}

運(yùn)行結(jié)果和上面保持一致。

文章出自:??愛科學(xué)的衛(wèi)斯理??,如有轉(zhuǎn)載本文請聯(lián)系愛科學(xué)的衛(wèi)斯理今日頭條號。


網(wǎng)頁標(biāo)題:SpringBoot2.6新特性:使用Java17的Record作為配置屬性
網(wǎng)頁地址:http://www.dlmjj.cn/article/cogcisj.html