This rule raises an issue when a Bean Validation constraint annotation (such as @NotNull, @Size, @Min,
@Pattern, etc.) is placed on a static field.
In Java, class-level members are referred to as static fields and static methods. The Bean Validation framework
(such as Hibernate Validator) will ignore constraints placed on any members declared with the static keyword.
For example, consider this configuration class:
class Configuration {
@NotNull
static String apiKey;
static void setApiKey(String key) {
apiKey = key;
}
}
The @NotNull constraint on the apiKey field will never be evaluated by the Bean Validation framework because the field is
declared as static. This means that apiKey could be set to null without any validation error being raised,
potentially leading to runtime errors elsewhere in the application.
Bean Validation is designed to work with object instances and their state. Static fields belong to the class itself, not to any particular instance, so they fall outside the scope of Bean Validation’s validation lifecycle.
When Bean Validation constraints are placed on static fields, developers may have a false sense of security, believing that the values are being validated when they are not. This can lead to several issues:
NullPointerException or other
exceptions at runtime.Move the constraint to an instance field. This is the most straightforward solution and aligns with how Bean Validation is designed to work.
public class User {
@NotNull
private String username;
@NotNull // Noncompliant
private static String defaultRole;
}
public class User {
@NotNull
private String username;
@NotNull
private String role;
public User() {
this.role = "USER"; // Set default in constructor
}
}