richzilla
richzilla

Reputation: 42002

Java annotations in odd places

Browsing through the source of a spring framework project i came across a method that looked like this:

@RequestMapping("primitive")
public @ResponseBody String primitive(@RequestParam Integer value) {
    return "Converted primitive " + value;
}

Being only a casual java user, ive not come across this before. As far as i was aware, the @ symbol preceded java annotations, yet there appear to be annotations in the method signature itself. What are the @ResponseBody and @RequestParam sections doing?

Upvotes: 3

Views: 251

Answers (3)

Tim Pote
Tim Pote

Reputation: 28029

The @ResponseBody is actually just a Plain-Jane Method annotation. You're allowed to put them after the scope keyword.

The @RequestParam annotation isn't part of the method signature. It's a Parameter Annotation.

Upvotes: 10

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

Annotations can be added in many places within Java code. A good way to find out exactly where is to look at the @Target meta-annotation. This annotation is applied to other annotations to describe to the compiler the locations that are valid for it to live. Anyways, the @Target annotation takes an array of ElementType, and this enumeration has all the valid locations to apply annotations to.

As of Java 6, the ElementType enum contains these values:

ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER and TYPE

In your example, @RequestMapping and @ResponseBody are both METHOD level annotations, even though they are not applied in the exact same location (one before the method scope modifier and one after), and @RequestParam is a PARAMETER level annotation.

Upvotes: 0

kevin628
kevin628

Reputation: 3526

Those annotations are specific to Spring, so you'll need to dive into Spring to learn all the annotations and what they mean.

Whenever I need to learn something new in Spring, I always jump back to the documentation: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/

It's good to read through that whole thing at least once in your life, if you plan on using Spring for enterprise development.

Upvotes: 2

Related Questions