context:annotation-config与context:component-scan的作用

context:annotation-config与context:component-scan的作用

一、context:annotation-config/

1.如果不配置context:annotation-config/的话,我们使用@Resource、@PostConstruct、@PreDestroy等注解就必须在配置文件声明CommonAnnotationBeanPostProcessor,使用@PersistenceContext注解就必须声明PersistenceAnnotationBeanPostProcessor,使用@Autowired注解就必须声明 AutowiredAnnotationBeanPostProcessor,如果想使用 @Required的注解就必须声明RequiredAnnotationBeanPostProcessor。

2.如果配置了context:annotation-config/,就相当于我们隐式地向spring注册了以上四个bean,我们不用声明这些bean就可以使用这些注解了。

二、<context:component-scan base-package="com.xxx"/>

1.context:component-scan除了具有context:annotation-config的功能,还可以在指定的包下扫描以及注册bean,还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能,所以使用了context:component-scan就可以将context:annotation-config移除。

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.hx"/>
posted @ 2021-12-23 11:03  AboutChristopher  阅读(100)  评论(0编辑  收藏  举报