这非常简单。我将把我的例子粘贴在这里,因为我已经把它写下来了,我很懒,不想夺走你的有趣体验:)
编辑:我认为你的问题是你没有用 @Valid 注释你的资源
所以我们开始吧:
您与验证器的合作是正确的。这些是我的:
public class CustomValidator implements ConstraintValidator<CustomValidation, String> {
@Override
public void initialize(CustomValidation constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("Validation called");
return false;
}
}
这是注释:
@Constraint(validatedBy = {CustomValidator.class})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface CustomValidation {
String message() default "Some message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
应用程序:
public class Application extends io.dropwizard.Application<Configuration>{
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
MetricRegistry metrics = environment.metrics();
environment.jersey().register(new HelloResource(metrics));
}
public static void main(String[] args) throws Exception {
new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
}
}
以及资源:
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class HelloResource {
private MetricRegistry service;
public HelloResource(MetricRegistry service) {
this.service = service;
}
@GET
public String hello() {
Timer timer = service.timer("test");
try(Context t = timer.time()) {
return "Hello World";
}
}
@GET
@Path("/test2")
public void test(@Valid @CustomValidation @QueryParam("arg") String test) {
System.out.println(test);
}
}
不要介意这些指标,它们与此无关。重要的是你需要告诉 DW 你想要验证什么。
在资源中,请参阅测试方法。我用@Valid(告诉DW进行验证)@CustomValidation(告诉DW使用什么验证器)来注释我需要的参数。
这实际上并不是 Dropwizard 功能,而是 hibernate 验证器实现。
它在底层的工作方式是,hibernate 在调用构造函数请求时动态创建 Validator 类。现在,如果您进行简单的验证(例如比较字符串),则效果非常好。如果您需要依赖项,那么它会变得稍微棘手一些。我也有一个例子,你可以在这里阅读:
通过 dropwizard 验证,我可以访问数据库来插入记录吗 https://stackoverflow.com/questions/32179991/with-dropwizard-validation-can-i-access-the-db-to-insert-a-record/33107377#33107377
此示例使用 guice,但它演示了如何将自己的创建机制挂接到验证中。这样您就可以控制验证器的创建,并使用数据源注入或初始化它们以访问您的数据库。
我希望能回答你的问题
Artur