Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom annotation to Spring MVC?

Can anyone explain what I need to do to implement my own annotation that would add functionality to my web requests?

For example:

@Controller
public class MyController {
    @RequestMapping("/abc")
    @RequiresSomeSpecialHandling
    public void handleSecureRequest() {
    }
}

Here @RequiresSomeSpecialHandling would be my own annotation that causes some special work to be done before or after the given web request /abc.

I know that on a very high level I would need to write a bean post processor, scan classes for my annotations, and inject custom mvc interceptors when needed. But are there any shortcuts to simplify this task? Especially for the two examples above.

Thanks in advance,

like image 916
rustyx Avatar asked Feb 03 '12 10:02

rustyx


2 Answers

This kind of Annotations, (that add additional functionality when invoking a method) looks like annotations that trigger an AOP Advice.

@see Spring Reference Chapter 7. Aspect Oriented Programming with Spring


The idea is to use the Annotation to trigger the AOP Advice.

like:

@Pointcut("@target(com.example.RequiresAuth)")
like image 127
Ralph Avatar answered Sep 27 '22 16:09

Ralph


Depends on what you want to do as a result of @RequiresSomeSpecialHandling. E.g. do you want it to influence request mappings or the invocation of the method (i.e. resolving method arguments, processing the return value)?

The support for annotated classes in Spring 3.1 became much more customizable. You can browse some examples in this repo.

Also keep in mind that a HandlerInterceptor in Spring 3.1 can cast the handler Object to HandlerMethod, which gives you access to the exact method including its annotations. That may be enough for what you need to do.

like image 27
Rossen Stoyanchev Avatar answered Sep 27 '22 16:09

Rossen Stoyanchev