Validating the POJO record with Micronaut not working

2.8k views Asked by At

Using Micronaut bean validation for the record class is not working

compile 'io.micronaut:micronaut-validation:2.2.1'

Record class

@Introspected
public record ProductViewModel
        (
                @JsonProperty("id")
                String id,

                @JsonProperty("name")
                @NotBlank
                @NotNull
                String name,

                @JsonProperty("description")
                @NotBlank
                String description,

                @JsonProperty("price")
                @NotBlank
                float price
        ) {
}

CURL

curl --location --request POST 'http://localhost:8084/api/v1/product' \
--header 'Content-Type: application/json' \
--data-raw '{
  "price": 1000,
 
  "description": "This is the description"
}'

Controller method

@Controller("/product")
@Validated
public class ProductController {

 private final IProductManager iProductManager;

    public ProductController(IProductManager iProductManager) {
        this.iProductManager = iProductManager;
    }
 @Post
 public Single<HttpResponse<?>> Create(@Body @Valid ProductViewModel model) {
        LOG.info(String.format("Controller --> Creating new product"));
        return iProductManager.Create(model).map(item -> HttpResponse.created(item));
    }
}

Error as

{
    "message": "model: Cannot validate view.model.product.ProductViewModel. No bean introspection present. Please add @Introspected to the class and ensure Micronaut annotation processing is enabled",
    "_links": {
        "self": {
            "href": "/api/v1/product",
            "templated": false
        }
    }
}
     

The annotation process is enabled.

Build.Gradle

plugins {
    id 'java'
}

group 'fete.bird'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.swagger.core.v3:swagger-annotations:2.1.5")
    implementation("javax.annotation:javax.annotation-api:1.3.2")
    testCompile group: 'junit', name: 'junit', version: '4.12'
    implementation 'org.mongodb:bson:4.2.0-beta1'
    implementation 'io.micronaut:core:1.0.0.RC2'
    implementation 'io.micronaut:micronaut-core:2.2.1'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.12.0'
    compile 'io.micronaut:micronaut-validation:2.2.1'
}
tasks.withType(JavaCompile).all {
    options.compilerArgs += ['--enable-preview']
}

tasks.withType(JavaExec) {
    jvmArgs += '--enable-preview'
}
1

There are 1 answers

0
San Jaisy On

If it is a separate module/project add the below dependency

compile "io.micronaut:micronaut-inject:2.2.2"
    annotationProcessor "io.micronaut:micronaut-inject-java:2.2.2"
    annotationProcessor "io.micronaut:micronaut-validation:2.2.2"

If the POJO are in the same project, update to the latest version of micronaut it is resolved here https://github.com/micronaut-projects/micronaut-core/issues/4712#event-4105835836