I have this custom annotation interface:
@Documented
@Constraint(validatedBy = NameValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface NameValidation {
String message() default "Name invalid";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
which has this NameValidator class:
public class NameValidator implements ConstraintValidator<NameValidation, String> {
@Autowired
private NicknameRepository nicknameRepository;
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
return nicknameRepository.existsById(1L);
}
}
NameValidator needs an autowired repository object to test a value in the Database.
Nickname repository
@Repository
public interface NicknameRepository extends JpaRepository<Nickname, Long> {
}
The Enitity and use of custom annotation:
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "Nickname")
@ToString
public class Nickname extends RepresentationModel<Nickname> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "nicknameValue")
private String nicknameValue;
@Column(name = "byUser")
@NameValidation(message = "Name is invalid") // using custom annotation
private String byUser;
}
When I run the application and try to add a new Nickname I get an error. The nickname repository in the NameValidator class is null.
This is the error I get.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: jakarta.validation.ValidationException: HV000028: Unexpected exception during isValid call.] with root cause
java.lang.NullPointerException: Cannot invoke "com.proj.repository.NicknameRepository.existsById(Object)" because "this.nicknameRepository" is null
I have tried many different answers on stackoverflow already such as adding @Service/@Component to NameValidator etc but for some reason Spring still isn't autowiring the nickname repository. Autowiring the nickname repository in other classes seems to work fine.
Did you try to add this configuration bean?