11

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,

rustyx
  • 80,671
  • 25
  • 200
  • 267

3 Answers3

4

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)")
Ralph
  • 118,862
  • 56
  • 287
  • 383
2

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.

Rossen Stoyanchev
  • 4,910
  • 23
  • 26
-3

If caching is one of your goals, take a look at the @Cacheable annotation (and its siblings @CachePut, @CacheEvict and @Caching), available as of Spring 3.1.

matsev
  • 32,104
  • 16
  • 121
  • 156
  • Sorry, your answer is useless to me. The @NoCache annotation in my example was about HTTP no-cache, not method cache, and it was just an example anyway. – rustyx Feb 03 '12 at 20:37