Java注释未应用我在其上设置的Java注释

时间:2018-10-12 23:13:38

标签: java java-ee

我有一个验证者注释

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = ContentAndExtensionValidator.class)
public @interface WithContentAndExtension {

    ContentAndExtension[] contentAndExtensions() default{};

    String message() default "File is not valid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

基本上,验证器将接受内容类型和文件扩展名对,并查看Multipart文件在这些对中是否有效。

我可以这样使用它

 methodName( @WithContentAndExtension(
    contentAndExtensions = {
    @ContentAndExtension(contentType = "text/xml", fileExtension = ".xml"),
    @ContentAndExtension(contentType = "application/octet-stream", fileExtension = ".bundle")
    },
    message = "File is not a valid XML or doesn't have .bundle extension" ) MultipartFile file){
 //Method definition here 
}

但是显然这太罗y了……如果我可以使用另一个注释对其进行抽象,那将是更理想的选择。

@Target( ElementType.PARAMETER )
@WithContentAndExtension(
    contentAndExtensions = {
    @ContentAndExtension(contentType = "text/xml", fileExtension = ".xml"),
    @ContentAndExtension(contentType = "application/octet-stream", fileExtension = ".bundle")
    },
    message = "File is not a valid XML or doesn't have .bundle extension"
)
@Retention(RetentionPolicy.SOURCE)
@Documented
public @interface ValidBundleFile {
}

并像这样使用它

methodName(@ValidBundleFile MultipartFile file){
  //Method implementation here 
}

对于如何正确地提取细节,我可能缺乏理解,并且我也在Google周围搜索,找不到任何内容。感谢您的建议。

0 个答案:

没有答案