Spring <context:annotation-config/> 解說
阿新 • • 發佈:2022-04-06
在spring中,如果我們想使用註解開發,那麼我們是需要建立對應的類的,即建立一個對應的bean物件,例如
-
若要使用@Autowired註解,那麼必須建立(宣告)(即注入到IOC容器中)
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>
-
以此類推,若要使用@Resource、@PostConstruct、@PreDestroy等註解就必須宣告CommonAnnotationBeanPostProcessor類
-
若想使用 @PersistenceContext 註解,就必須宣告PersistenceAnnotationBeanPostProcessor的Bean。
-
若想使用 @Required 的註解,就必須宣告RequiredAnnotationBeanPostProcessor的Bean。
註冊這4個BeanPostProcessor的作用,就是為了你的系統能夠識別相應的註解。那麼, 當我們開發時難道一個一個去宣告嗎? 這就破壞了輪子理論(哈哈)
於是聰明的Spring就給我們提供了 <context:annotation-config/> 這種簡化配置的方式,它會自動幫我們完成這些宣告。不過我們一般不用它,我們一般用 <context:component-scan base-package="com.xxx"/> 因為它不僅有上面的功能,還具有自動掃描以及自動註冊bean的功能