Java中@RequiredArgsConstructor注解的基本用法
前言
從源碼中學習,事因是看到項目代碼中有所引用
@RequiredArgsConstructor
是 Lombok 提供的一個注解,用于自動生成一個包含所有 final 字段和帶有 @NonNull 注解字段的構造函數(shù)
這可以減少樣板代碼,尤其是在需要依賴注入時
1. 基本知識
Lombok 是一個 Java 庫,通過注解簡化代碼
常用注解包括 @Getter, @Setter, @ToString, @EqualsAndHashCode, 和 @Data 等
針對@RequiredArgsConstructor 注解會生成一個包含所有 final 字段和帶有 @NonNull 注解字段的構造函數(shù)
這對于構造必須初始化這些字段的對象非常有用
基本的語法如下:
@RequiredArgsConstructor public class MyClass { private final String name; private final int age; private String address; @NonNull private String phoneNumber; }
對應生成的構造函數(shù)如下:
public MyClass(String name, int age, String phoneNumber) { this.name = name; this.age = age; this.phoneNumber = phoneNumber; }
對應需要注意的事項如下:
字段的順序
:生成的構造函數(shù)中的參數(shù)順序是按照字段在類中定義的順序@NonNull
注解:如果某個字段帶有 @NonNull 注解,它也會包含在構造函數(shù)中,即使它不是 final 的。
與其他構造函數(shù)沖突:如果手動定義了構造函數(shù),@RequiredArgsConstructor 生成的構造函數(shù)可能會與其沖突
與其他注解比較:
@NoArgsConstructor
:生成一個無參構造函數(shù)。@AllArgsConstructor
:生成一個包含所有字段(包括非 final 字段)的構造函數(shù)
2. 源碼解讀
先看源碼的對應屬性
對應的屬性分析如下:
staticName
:
- 設置了這個屬性,會生成一個靜態(tài)方法,該方法調用私有構造函數(shù)
- 這個靜態(tài)方法主要用于推斷類型參數(shù)
onConstructor
:
- 允許在生成的構造函數(shù)上添加指定的注解
- JDK 7 和 JDK 8 的語法稍有不同。
access
:
- 設置構造函數(shù)的訪問級別
- 默認是 public,可以設置為 private, protected 或 package
針對源碼結合以下Demo進行展示
3. Demo
3.1 簡易Demo
import lombok.NonNull; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class test { private final String firstName; private final String lastName; @NonNull private String email; private int age; public static void main(String[] args) { // 正確使用示例 test person = new test("碼農(nóng)", "研究僧", "https://blog.csdn.net/weixin_47872288"); System.out.println("Person created: " + person); // 錯誤使用示例(會導致編譯錯誤) // Person person2 = new Person("Jane", "Doe"); } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", age=" + age + '}'; } }
明確需要3個屬性,不可超過4個
再者對應的字段屬性是按照順序的,如果更換順序會出現(xiàn)如下場景:
test person = new test("碼農(nóng)","https://blog.csdn.net/weixin_47872288","研究僧");
3.2 staticName屬性
@RequiredArgsConstructor(staticName = "of")
會生成一個靜態(tài)方法 of 來實例化對象,而不是直接調用構造函數(shù)
import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(staticName = "of") public class test { private final String firstName; private final String lastName; private final String email; public static void main(String[] args) { test example = test.of("碼農(nóng)","研究僧","https://blog.csdn.net/weixin_47872288"); System.out.println(example); } @Override public String toString() { return "StaticConstructorExample{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
截圖如下:
3.3 onConstructor屬性
@RequiredArgsConstructor(onConstructor_ = @__(@CustomAnnotation("Custom Constructor")))
會在生成的構造函數(shù)上添加 @CustomAnnotation
import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.CONSTRUCTOR}) @Retention(RetentionPolicy.RUNTIME) @interface CustomAnnotation { String value(); } @RequiredArgsConstructor(onConstructor_ = @__(@CustomAnnotation("Custom Constructor"))) public class test { private final String firstName; private final String lastName; private final String email; public static void main(String[] args) { test example = new test("碼農(nóng)","研究僧","https://blog.csdn.net/weixin_47872288"); System.out.println(example); } @Override public String toString() { return "StaticConstructorExample{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
3.4 access屬性
@RequiredArgsConstructor(access = AccessLevel.PRIVATE, staticName = "of") public class test { private final String firstName; private final String lastName; private final String email; public static void main(String[] args) { test example = test.of("碼農(nóng)", "研究僧", "https://blog.csdn.net/weixin_47872288"); System.out.println(example); } @Override public String toString() { return "StaticConstructorExample{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
不需要構造函數(shù)是私有的,可以將構造函數(shù)的訪問級別設置為 public 或 protected,直接進行new
但是我的private它竟然可以new(神奇=-=)
4. @AllArgsConstructor比較
使用 @RequiredArgsConstructor
時,只有 final 字段和 @NonNull 字段會被初始化
但是@AllArgsConstructor
生成一個構造函數(shù),該構造函數(shù)包含類中所有字段,無論它們是否為 final 或帶有 @NonNull 注解
@AllArgsConstructor public class test { private final String firstName; private String lastName; @NonNull private String email; private int age; public static void main(String[] args) { // 正確使用示例 test person = new test("碼農(nóng)","研究僧","https://blog.csdn.net/weixin_47872288",18); System.out.println("Person created: " + person); // 錯誤使用示例(會導致編譯錯誤) // Person person2 = new Person("Jane", "Doe"); } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", age=" + age + '}'; } }
截圖如下:(必須要有四個參數(shù))
這兩者都可以實用構造函數(shù)注入,但推薦使用@RequiredArgsConstructor
,因為它只會初始化那些在創(chuàng)建對象時必需的字段
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- spring中的特殊注解@RequiredArgsConstructor詳解
- 使用@RequiredArgsConstructor注解來取代繁瑣的@Autowrired
- 解讀@NoArgsConstructor,@AllArgsConstructor,@RequiredArgsConstructor的區(qū)別及在springboot常用地方
- Java中的@RequiredArgsConstructor注解詳解
- @RequiredArgsConstructor如何實現(xiàn)構造器注入
- springboot @RequiredArgsConstructor的概念與使用方式
- Java中@RequiredArgsConstructor使用詳解
相關文章
IDEA的Web項目右鍵無法創(chuàng)建Servlet問題解決辦法
這篇文章主要介紹了IDEA的Web項目右鍵無法創(chuàng)建Servlet問題解決辦法的相關資料,在IDEA中新建Servlet時發(fā)現(xiàn)缺失選項,可以通過在pom.xml文件中添加servlet依賴解決,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-10-10關于JavaEE匿名內(nèi)部類和Lambda表達式的注意事項
這篇文章主要介紹了關于JavaEE匿名內(nèi)部類和Lambda表達式的注意事項,匿名內(nèi)部類顧名思義是沒有修飾符甚至沒有名稱的內(nèi)部類,使用匿名內(nèi)部類需要注意哪些地方,我們一起來看看吧2023-03-03基于Java class對象說明、Java 靜態(tài)變量聲明和賦值說明(詳解)
下面小編就為大家?guī)硪黄贘ava class對象說明、Java 靜態(tài)變量聲明和賦值說明(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06java 漢諾塔Hanoi遞歸、非遞歸(仿系統(tǒng)遞歸)和非遞歸規(guī)律 實現(xiàn)代碼
漢諾塔(Hanoi) 算法Java實現(xiàn)。通過三個函數(shù),分別對Hanoi進行遞歸、非遞歸和非遞歸規(guī)律實現(xiàn)。2013-05-05SpringBoot中使用MQTT實現(xiàn)消息的訂閱和發(fā)布(示例代碼)
這篇文章主要介紹了SpringBoot中使用MQTT實現(xiàn)消息的訂閱和發(fā)布的相關知識,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-06-06