context:component-scan base-package="" 与context:annotation-config

在spring-servlet.xml或者applicationContext.xml中声明<context:component-scanpackage="com.a"/>可以隐式地向该上下文注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor ,从而使得该上下文中的bean都可以使用@Resource、@autowired等注解引用其他的bean(当然一并引入还有其他功能的注解,这里就不一一列举了),这个功能相当于声明<context:annotation-config/>,此外,<context:component-scan package="com.a"/>中的package="com.a",表示可以扫描com.a包下的类,将添加了@component等注解的类注册为上下文中的一个bean,如果写<context:component-scan package="com.b"/>,则只启用@Resource等注解,但是不会通过@component注解来注册com.a包中的bean。例如

package com.a;

@Component

public class A{

  @Resource

  com.b.User user;

}

如果写 <context:component-scan package="com.b" />,那么User类的bean可以注入(假如存在这个bean),但是@Component注解不会起作用,因此A不会注册为一个bean。

<context:component-scan package="com.a" />要求必须指定包名,如果仅仅是希望

引入@resource @autowired等注解功能,使用

<context:annotation-config />即可。

总之<context:component-scan package="com.a" />包含了

<context:annotation-config />的功能。

猜你喜欢

转载自blog.csdn.net/mr_orange_klj/article/details/80320723