关于Spring中context:annotation-config配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Beckio/article/details/79421335

想要Spring支持注解的方式,我们需要在spring配置文件中添加以下配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="Index of /schema/context"
       xsi:schemaLocation="Index of /schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
Index of /schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>

</beans>

<context:annotation-config/>这条配置,他的作用是向 Spring 容器注册

AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor

这 4 个BeanPostProcessor。
注册这4个BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。
例如:如果你想使用@Autowired注解,那么就必须事先在Spring容器中声明 AutowiredAnnotationBeanPostProcessor Bean。传统声明方式如下:

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/> 

如果想使用@Resource、@PostConstruct、@PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor

<bean class="org.springframework.beans.factory.annotation. CommonAnnotationBeanPostProcessor"/>

如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。

<bean class="org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor"/> 

如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。

同样,传统的声明方式如下:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 

一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供<context:annotation-config/>的简化配置方式,自动帮你完成声明
不过,我们使用注解一般都会配置扫描包路径选项<context:component-scan base-package=”XX.XX”/>
该配置项其实也包含了自动注入上述processor的功能,因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。
比如:

<context:component-scan base-package="XXController, XXService, XXDao" />

就把controller包下 service包下 dao包下的注解全部扫描了。

参考:https://www.zhihu.com/question/39356740/answer/80926247

猜你喜欢

转载自blog.csdn.net/Beckio/article/details/79421335
今日推荐