Jochen Pier
Jochen Pier

Reputation: 175

Spring: Create Meta-Annotation for @ModelAttribute

I have a lot of controllers with this code:

@RequestMapping("/test1")
public String test (@ModelAttribute("page") Page page) {
...
}

@RequestMapping("/test2")
public String test2 (@ModelAttribute("page") Page page) {
...
}

Is it possible to create a Meta-Annotation in Spring (4.3) that shortens this Annotation like this:

@RequestMapping("/test3")
public String test2 (@MyCustom Page page) {
...
}

So @ModelAttribute("page") will become @MyCustom?

Upvotes: 1

Views: 233

Answers (2)

Jochen Pier
Jochen Pier

Reputation: 175

I think I found an elegant solution for this: We use the "HandlerMethodArgumentResolver" to check for Arguments of type "Page". If we found one, we get it out of the model and that's it.

This leads to this:

@RequestMapping("/test3")
public String test2 (Page page) {
...
}

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

Unfortunately that won't work work. As you can see in the sources, ModelAttribute is annotated

@Target({ElementType.PARAMETER, ElementType.METHOD})

which means it can be applied to methods and method parameters only. For a meta annotation, it would have to be applied on type level.

See Spring Annotation Programming Model for details, but basically this is an edge case where Meta annotations just don't work.

Upvotes: 1

Related Questions