<context:annotation-config/>和<context:component-scan/>

本文介绍了在Spring框架中使用&lt;context:annotation-config/&gt;和&lt;context:component-scan/&gt;进行配置的方式,解释了它们如何帮助自动注册如@AutowiredAnnotationBeanPostProcessor等常用BeanPostProcessor,简化开发流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<context:annotation-config/>和<context:component-scan/>

 

在配置文件中加上这个配置后,就会在spring中注册下面4个BeanPostProcessor

1. AutowiredAnnotationBeanPostProcessor

2. CommonAnnotationBeanPostProcessor

3. PersistenceAnnotationBeanPostProcessor 

4. RequiredAnnotationBeanPostProcessor 

 

 

 

为什么要注册这些BeanPostProcessor

 

1. 如果要使用@Autowired,就要实现在容器中注册 AutowiredAnnotationBeanPostProcessor

 

2. 如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须注册 CommonAnnotationBeanPostProcessor

 

3. 如果想使用@PersistenceContext注解,就必须注册PersistenceAnnotationBeanPostProcessor

 

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

 

 

 

当然,可以用下面这种方式注册

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

这种方式的优点是单独明确,缺点是每个使用都要注册一次

 

因为这些注释通常都会用到,所以直接用<context:annotation-config/>,自动帮你注册了这些,更加方便开发

 

 

 

还有个不需要<context:annotation-config/>的方法

 

一般我们要用<context:component-scan base-package=”XX.XX”/> 来扫描包,有了该配置就能自动注入上面的几个BeanPostProcessor,所以加上这个扫描包的配置后,就能把<context:annotation-config/>去掉了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值