Impossibile creare meta-annotazioni per @RequestBody in Springboot

Aug 15 2020

Voglio creare una meta-annotazione, chiamata @QueryRequest, per Spring @RequestBodycome mostrato di seguito.

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@RequestBody
public @interface QueryRequest {
}

Tuttavia, genera un errore di compilazione chiamato, java: annotation type not applicable to this kind of declaration

Quando ho cercato in Internet, mi dice di verificare il @Targettipo corretto . Ad ogni modo, come puoi già vedere i miei valori @Targete @Retention, sono uguali a quelli di Spring @RequestBody, ma viene comunque lanciato l'errore sopra.

Ho creato con successo meta-annotazioni per @Target=ElementType.METHODo ElementType.TYPEtipi, ma non sono riuscito a lavorare sopra l'annotazione.

Qualcuno sa cosa c'è di sbagliato nella meta-annotazione di cui sopra?

Risposte

1 DanielJacob Aug 16 2020 at 02:15

Poiché @RequestBody è annotato @Target(ElementType.PARAMETER), puoi solo aggiungere questa annotazione su un parametro. Qui stai cercando di applicare l'annotazione su un'annotazione. Per ottenere ciò @RequestBodyavrebbe dovuto essere annotato con @Target(ElementType.ANNOTATION_TYPE)o con @Target(ElementType.TYPE).

Ad esempio, questo codice non funzionerà perché non è possibile annotare QueryRequest su un'annotazione:

@Target(ElementType.PARAMETER)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface QueryRequest {
}
@Target(ElementType.ANNOTATION_TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@QueryRequest
@interface NextQueryRequest

Tuttavia questo funzionerà, perché stai consentendo a QueryResult di essere inserito in un'annotazione

@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface QueryRequest {
}
@Target(ElementType.ANNOTATION_TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@QueryRequest
@interface NextQueryRequest

 @Target(ElementType.ANNOTATION_TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface QueryRequest {
}
@Target(ElementType.ANNOTATION_TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@QueryRequest
@interface NextQueryRequest
isuru89 Aug 16 2020 at 10:19

@Daniel ha spiegato perché questo accade con un esempio.

Inoltre, chiunque stia cercando una soluzione alternativa dovrebbe leggere questa risposta come @Michiel menzionato sopra.https://stackoverflow.com/a/40861154/2148365