21

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?

Community
  • 1
  • 1
ipavlic
  • 4,906
  • 10
  • 40
  • 77

2 Answers2

17

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.

Jose Luis Martin
  • 10,459
  • 1
  • 37
  • 38
1

Spring context understand annotation by set of classes which implements bean post processor interface. so to handle different type of annotation we need to add different annotation bean post processors.

if you add <context:annotation-config> in you configuration xml then you need not to add any annotation bean post processors.

Post processor provide methods to do pre and post processing for each bean initialization. you can write your own bean post processors to do custom processing by created a bean which implements BeanPostProcessor interface.

Abhishek Kumar
  • 229
  • 1
  • 5