spring的context:component-scan必须配置扫描子包问题

未使用spring-boot,系统里有类实现InitializingBean,但需依赖注入一对象,为util:properties,使用的@Autowired,这个类作为bean配置在spring配置文件中。刚开始只配置了context:component-scan扫描父包,发现不能拿到依赖注入的util:properties,即依赖的properties对象为空。后来新增一个context:component-scan,将子包也配置到里面,就正常了。详细原因还在分析中,有点颠覆之前的认识了。

原工程里也配置了<context-annotation-config/>,增加与删除它对系统没影响。

(1. 当这两个配置同时配置时,<context-annotation-config />将失效,以<context:component-scan base-package="" />为准!     

2. @Component、@Controller、@Service、@Repository这些注解本身并不具有声明注册bean的功能,在没有<context:component-scan>扫描解析之前是没有任何作用的!

<context:annotation-config/>的作用

      当我们需要使用BeanPostProcessor时,使用@Autowired注解,必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessor的Bean:

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

  使用 @Required注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean:

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

  类似地,使用@Resource、@PostConstruct、@PreDestroy等注解就必须声明 CommonAnnotationBeanPostProcessor;使用@PersistenceContext注解,就必须声明 PersistenceAnnotationBeanPostProcessor的Bean。
  Spring为我们提供了一种极为方便注册这些BeanPostProcessor的方式,即使用<context:annotation- config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。如下:

<context:annotation-config/> 

  另,在我们使用注解时一般都会配置扫描包路径选项:

<context:component-scan base-package="pack.pack"/>

  该配置项其实也包含了自动注入上述processor的功能,因此当使用<context:component-scan/>后,即可将<context:annotation-config/>省去。

)

需依赖注入的对象所在的spring配置文件里有,default-lazy-init="true",跟它也没关系。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值