使用 Micronaut 验证 POJO 记录不起作用 [英] Validating the POJO record with Micronaut not working
本文介绍了使用 Micronaut 验证 POJO 记录不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对记录类使用 Micronaut bean 验证不起作用
Using Micronaut bean validation for the record class is not working
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 --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));
}
}
错误为
{
"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
}
}
}
注释过程已启用.
Build.Gradle
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'
}
推荐答案
如果是单独的模块/项目添加下面的依赖
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"
如果POJO在同一个项目,更新到最新版本的micronaut,这里解决https://github.com/micronaut-projects/micronaut-core/issues/4712#event-4105835836
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
这篇关于使用 Micronaut 验证 POJO 记录不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文