如何Spring注解工作? [英] How do Spring annotations work?
问题描述
作为后续行动,我的previous问题上的类加载
As a follow-up to my previous questions on classloading
- How is the Classloader for a class chosen?
- How Classloader determines which classes it can load?
- Where does bytecode injection happen?
我很好奇怎么做注解在流行的Spring框架。
I'm curious about how do annotations work in a popular Spring framework.
据我了解,两种机制可以用于:
As far as I understand, two mechanisms might be used:
1。在类加载字节code注射液
春季可以使用自己的类加载器来加载所需的类。在运行时,当类被加载和Spring决定了它有一些相应的注释,它注入字节code到附加属性或行为添加到类。
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.
因此,与 @Controller
注释控制器可能会被更改扩展一些控制器的基类,当与注释功能可能会改变来实现路由@RequestMapping
。
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。用于实例化的反思
@Autowired
可通过反射在运行时被BeanFactory读取实例化顺序的关怀和实例化配置的属性。
@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;
}
}
问题
如何Spring注解真的管用吗?
Question
How do Spring annotations really work?
推荐答案
春天是开源的,所以你不必理解它是如何工作的,看看里面:
Spring is open source so you don't need to figure how it work, look inside:
-
RequestMapping
注释由RequestMappingHandlerMapping
处理,请参阅getMappingForMethod
方法。
RequestMapping
annotation is handled byRequestMappingHandlerMapping
, seegetMappingForMethod
method.
自动装配注释由 AutowiredAnnotationBeanPostProcessor
处理,请参阅 processInjection
方法。
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.
这篇关于如何Spring注解工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!