Spring注解是如何生效的?
現在大部分開發已經采用Spring Boot了,少了很多配置文件,方便了許多。以前在使用注解,比如@Autowired、@Resource 或者事務相關的一些注解時,我們會首先在配置文件里面加入這樣的配置:
context:component-scan
context:annotation-config
tx:annotation-driven
這樣就能告訴Spring容器在啟動的時候,把相應的后處理器(BeanPostProcessor)初始化,交給Spring容器來管理,然后通過這些后處理器 去實現 各種注解(的功能),比如實現:@Autowired 默認 按類型注入屬性 。具體來說,@Autowired 是Spring框架提供的注解,它是由AutowiredAnnotationBeanPostProcessor 后處理器實現的;@Resource 是JDK里面提供的注解,它由CommonAnnotationBeanPostProcessor實現注入的功能。
那使用了Spring Boot之后,幾乎已經看不到上述配置了,簡單來說:Spring Boot應用程序在啟動的時候,默認加載了一批BeanPostProcessor,這樣就可以實現這些注解的功能了。這是怎么做到的呢?
我們知道,Spring Boot應用程序會在Application啟動類中標上 @SpringBootApplication 注解。這個注解包含了三個子注解:
- SpringBootConfiguration 將Application啟動類作為Bean類注入到Spring容器中
- EnableAutoConfiguration 實現自動配置功能
- ComponentScan 實現自動掃描的功能,具體來說:就是告訴Spring容器注冊"一些"Bean后處理器,從而能夠支持各種注解。
比如說,要想讓@Autowired生效,Spring容器必須加載了AutowiredAnnotationBeanPostProcessor 后處理器,看這個類的源碼注釋:
A default AutowiredAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags.
因此,只要我們在XML配置文件里面配置了 context:component-scan
,AutowiredAnnotationBeanPostProcessor 就能被注冊到Spring容器中。而使用Spring Boot之后,由@SpringBootApplication注解下面的@ComponentScan 完成了同樣的功能。這就是不需要我們自己在XML配置文件里面寫一行 context:component-scan
配置的原因。
類似地:CommonAnnotationBeanPostProcessor 實現了 @Resource 注解的功能,看看它的類源碼注釋可知:它負責實現@PostConstruct、@PreDestroy、@Resource等注解,配置了 @ComponentScan 就能將它注冊到Spring容器中。
最后再來說說開啟事務的注解@EnableTransactionManagement:
當我們在Application啟動類 上標注 @EnableTransactionManagement 時,就表示開啟事務,它等價於XML配置方式 tx:annotation-driven
。