如何配置IntelliJ IDEA,在Lombok生成构造器违反@NotNull/@Nullable契约时告警?
Got it, let's sort out why IntelliJ isn't flagging null violations for your Lombok-generated constructors—even though you've set lombok.NonNull as your @NotNull annotation and already get alerts for getters/setters. Here's the step-by-step fix:
1. Verify Annotation Processing is Enabled
First, make sure IntelliJ is properly handling Lombok annotations (this is a common overlooked step):
- Go to
Settings > Build, Execution, Deployment > Compiler > Annotation Processors - Check the box for Enable annotation processing
- If you use Maven/Gradle, ensure your build tool is configured to work with IntelliJ's annotation processor (this ensures IDE picks up Lombok-generated code correctly)
2. Turn On Constructor Parameter Checks in Inspections
This is almost certainly the missing piece—you need to explicitly tell IntelliJ to validate constructor parameters for @NotNull violations:
- Navigate back to
Settings > Editor > Inspections > Java > Probable bugs > @NotNull/@Nullable problems - On the right-hand panel, scroll through the options and make sure Check constructor parameters is checked (it might be disabled by default)
- Double-check your annotation mapping here too: click
Configure annotations, confirmlombok.NonNullis set as your @NotNull annotation, and that it's mapped for both fields and method/constructor parameters
3. Refresh IntelliJ's Cache
Sometimes old cache data blocks new settings from taking effect:
- Go to
File > Invalidate Caches... - Select Invalidate and Restart from the popup—this clears stale cached data and restarts the IDE to apply your changes
Test the Fix
To confirm everything works, create a quick test class:
import lombok.NonNull; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class TestConstructorNullCheck { @NonNull private final String username; public static void main(String[] args) { // This line should now trigger a @NotNull violation alert TestConstructorNullCheck test = new TestConstructorNullCheck(null); } }
If all settings are correct, the null passed to the constructor will be highlighted with a warning about violating the @NonNull contract.
内容的提问来源于stack exchange,提问作者Eric

