Search code examples
javaspring-bootspring-mvcspring-data-jpaspring-rest

java.lang.ClassNotFoundException: javax.validation.Validation



import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import lombok.extern.slf4j.Slf4j;
import com.example.demo.entity.Country;
import com.example.demo.repository.CountryRepository;

@Slf4j
@RestController
@RequestMapping("/countries")
public class CountryController {
    @Autowired
    private Country country;
    
    @PostMapping
    public Country addCountry(@RequestBody @Valid Country country){
        log.info("Started");
        // Create validator factory

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        // Validation is done against the annotations defined in country bean
        Set<ConstraintViolation<Country>> violations = validator.validate(country);
        List<String> errors = new ArrayList<String>();
        // Accumulate all errors in an ArrayList of type String
        for (ConstraintViolation<Country> violation : violations) {
            errors.add(violation.getMessage());
        }
        // Throw exception so that the user of this web service receives appropriate error message
        if (violations.size() > 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.toString());
        }
        return country;
    }
        
}

I'm getting the error java.lang.ClassNotFoundException: javax.validation.Validation whenever I send a post request. I tried writing this in git bash -> curl -i -H 'Content-Type: application/json' -X POST -s -d '{"code":"IN","nae":"India"}' http://localhost:8080/countries and I got the error


Solution

  • You have to add an implementation of javax.validation API to your project's dependencies. If you are building it with maven, you can add the following in the dependencies section of your pom file.

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.1.2.Final</version>
    </dependency>