Injecting a bean in Customer ConstraintValidator. No invocation. Is it possible?

I have created Custom ContrainValidator and added the code below. I am passing a bean where I have all my Validation logic. However, it is not working. The Validator is not being invoked.

I have also added my controller class. Somehow code is not flowing in the validator.

ValidCustomClass class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package com.validation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Constraint(validatedBy = MyValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface ValidCustomClass {
String message() default "Invalid request.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
</code>
<code>package com.validation; import jakarta.validation.Constraint; import jakarta.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Constraint(validatedBy = MyValidator.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) public @interface ValidCustomClass { String message() default "Invalid request."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } </code>
package com.validation;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Constraint(validatedBy = MyValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface ValidCustomClass {
    String message() default "Invalid request.";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Validator class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package com.validation;
import com.model.request.CreateRequest;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyValidator implements ConstraintValidator<ValidCustomClass, CreateRequest> {
private static final String MY_REGEX = "^(.+)@(.+)$";
private final MyService myService;
public MyValidator(MyService myService) {
this.myService = myService;
}
@Override
public void initialize(ValidCustomClass constraintAnnotation) {
// DO nothing here
}
@Override
public boolean isValid(final CreateRequest value, final ConstraintValidatorContext context) {
if (dosSomething(value)) return false;
return true;
}
}
</code>
<code>package com.validation; import com.model.request.CreateRequest; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MyValidator implements ConstraintValidator<ValidCustomClass, CreateRequest> { private static final String MY_REGEX = "^(.+)@(.+)$"; private final MyService myService; public MyValidator(MyService myService) { this.myService = myService; } @Override public void initialize(ValidCustomClass constraintAnnotation) { // DO nothing here } @Override public boolean isValid(final CreateRequest value, final ConstraintValidatorContext context) { if (dosSomething(value)) return false; return true; } } </code>
package com.validation;

import com.model.request.CreateRequest;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyValidator implements ConstraintValidator<ValidCustomClass, CreateRequest> {

    private static final String MY_REGEX = "^(.+)@(.+)$";

    private final MyService myService;

    public MyValidator(MyService myService) {
        this.myService = myService;
    }

    @Override
    public void initialize(ValidCustomClass constraintAnnotation) {
        // DO nothing here
    }

    @Override
    public boolean isValid(final CreateRequest value, final ConstraintValidatorContext context) {
        if (dosSomething(value)) return false;
        return true;
    }
}

Controller class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package com.controller;
import com.model.request.CreateRequest;
import com.model.response.MyResponse;
import com.service.MyService;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
@RequestMapping("/endpoint")
public class MyController {
private final MyService myService;
MyController(MyService myService) {
this. myService = myService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public MyResponse create(@RequestBody @Valid CreateRequest request) throws Exception {
return myService.create(request);
}
}
</code>
<code>package com.controller; import com.model.request.CreateRequest; import com.model.response.MyResponse; import com.service.MyService; import jakarta.validation.constraints.NotNull; import jakarta.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @Validated @RequestMapping("/endpoint") public class MyController { private final MyService myService; MyController(MyService myService) { this. myService = myService; } @PostMapping @ResponseStatus(HttpStatus.CREATED) public MyResponse create(@RequestBody @Valid CreateRequest request) throws Exception { return myService.create(request); } } </code>
package com.controller;

import com.model.request.CreateRequest;
import com.model.response.MyResponse;
import com.service.MyService;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
@RequestMapping("/endpoint")
public class MyController {

    private final MyService myService;

    MyController(MyService myService) {
        this. myService = myService;
    }


    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public MyResponse create(@RequestBody @Valid CreateRequest request) throws Exception {
        return myService.create(request);
    }
}

finally I have added @ValidCustomClass on CreateRequest.

Am I missing something here? There are no errors but the validator in not invoked.

What have I tried?

  • I tried creating default constructor and assigning null to myService in it as suggested in many of the stackoverflow question but I observed that the default constructor is invoked after the parameterised assigning myService null leading to NullPointerException
  • I tried using @Autowired but somehow it did not work either. I thought I need to make MyValidator a bean as well but that also did not work.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật