使用 Micronaut 验证 POJO 记录不起作用

2023-12-14

使用 Micronaut bean 验证记录类不起作用

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

记录课

@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("/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
        }
    }
}
     

注释过程已启用。

构建.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'
}

如果它是一个单独的模块/项目,请添加以下依赖项

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"

如果POJO在同一个项目中,更新到micronaut最新版本就可以在这里解决https://github.com/micronaut-projects/micronaut-core/issues/4712#event-4105835836

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Micronaut 验证 POJO 记录不起作用 的相关文章

随机推荐