您的位置:首页 > 其它

<context:component-scan base-package="com.a" /> 与<context:annotation-config />

2017-11-26 00:33 555 查看
在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
/>即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐