How do Spring annotations work?

ipavlic picture ipavlic · Mar 7, 2013 · Viewed 8.7k times · Source

Motivation

As a follow-up to my previous questions on classloading

I'm curious about how do annotations work in a popular Spring framework.

Possible solution

As far as I understand, two mechanisms might be used:

1. Bytecode injection on classloading

Spring could use its own classloader to load required classes. At runtime, when the class is loaded and Spring determines it has some appropriate annotation, it injects bytecode to add additional properties or behavior to the class.

So a controller annotated with @Controller might be changed to extend some controller base class and a function might be changed to implement routing when annotated with @RequestMapping.

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }
}

2. Reflection used for instantiation

@Autowired could be read by reflection at runtime by the BeanFactory to take care of the instantiation order and instantiate the configured properties.

public class Customer 
{
    private Person person;

    @Autowired
    public void setPerson(Person person) {
        this.person = person;
    }
}

Question

How do Spring annotations really work?

Answer

Jose Luis Martin picture Jose Luis Martin · Mar 7, 2013

Spring is open source so you don't need to figure how it work, look inside:

  • RequestMapping annotation is handled by RequestMappingHandlerMapping, see getMappingForMethod method.

  • Autowired annotation is handled by AutowiredAnnotationBeanPostProcessor, see processInjection method.

Both use reflection to get annotation data and build the handler mapping info in the first case or populate the bean in the second one.