Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Spring's @RequestMapping work?

Tags:

java

spring

aop

As you know @RequestMapping get used to intercept a HttpServletRequest.

I want to know how @Controller @RequestMapping together can bind a request coming from a client to a specific method inside a java class ?

I want to write a similar java application to do the same functionality, Imagine We have a class like this:

@Actor
public class JavaForever {

  @Department(value="IT")
  public void departmentIT(){...}

  @Department(value="Physic")
  public void departmentPhysic(){...}
}

And a StudentBean class :

public class StudentBean {

    private String department;
    private Integer age;
    //Other class variable
    //Getters & Setters
}

and finally we have a Test class like this:

public class TestApplication {
   //getStudentFromDatabaseMethod() implementation here

   public static void main(String[] agrs){
     List<StudentBean> allStudents = new TestApplication().getStudentFromDatabaseMethod();
   //other codes
   }
}

As you see getStudentFromDatabaseMethod() returns List< StudentBean>, now the question is how we can force this method to get intercept with our @Department annotation which resides in JavaForever class before it returns any value ...

how we can do this ???

like image 359
Mehdi Avatar asked Feb 07 '14 19:02

Mehdi


1 Answers

Here is a broad overview

  1. You identify the classes for Spring to search (for annotations).
  2. Spring finds your @Controller and @RequestMapping annotations.
  3. Spring builds a map of the URL values from the @RequestMapping annotations.
  4. At runtime, when a request is received by Spring, it searches the map for the URL. When it finds the URL, it calls the method that is marked with the @RequestMapping.

Summary:

  • Annotations don't do anything. They are markers for other classes that do stuff.

Start by reading an Annotation Tutorial. You will need to scan your classes (during startup) for your annotations (using reflection) then handle them appropriately.

like image 177
DwB Avatar answered Sep 28 '22 06:09

DwB