今天偶然看见项目中的applicationContext.xml配置文件,就想起来曾经学习的时候比较困惑一个问题:<context:component-scan />和<context:annotation-config/> 这两种注解配置到底有啥区别??。。其实到今天如果不是看帖子估计我还是迷迷糊糊的,不喜欢探究的程序员不是好java工程师。。
首先从<context:annotation-config/>说起
<context:annotation-config/>篇
他的作用是式地向
AutowiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor、
RequiredAnnotationBeanPostProcessor
注册这4个
<bean
如果想使用@ Resource
如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBea
如果想使用
<bean
一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供<context:annotation-config/>的简化配置方式,自动帮你完成声明。
但是你可能也注意到了现在的注解很多,仅仅这几个注解恐怕是不够的,不怕一万就怕万一。。。。。。。。。。。。。。
比如这几个就没有:@component,@service,@Repository,@Controller
<context:component-scan />篇
@Component
、
@Service
和@Controller
。
@Component
是所有受Spring管理组件的通用形式;而
@Repository
、
@Service
和@Controller
则是
@Component
的细化,用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。也就是说,你能用
@Component
来注解你的组件类,但如果用
@Repository
、
@Service
@Controller
来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。例如,这些典型化注解可以成为理想的切入点目标。当然,在Spring Framework以后的版本中, @Repository
、
@Service
和@Controller
也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用
@Component
还是
@Service
,那
@Service
显然是更好的选择。同样的,就像前面说的那样,@Repository
已经能在持久化层中进行异常转换时被作为标记使用了。”其他的先不说就单单说他的包过滤就感觉很好:
</context:component-scan>
Filter Type | Examples Expression | Description |
annotation | org.example.SomeAnnotation | 符合SomeAnnoation的target class |
assignable | org.example.SomeClass | 指定class或interface的全名 |
aspectj | org.example..*Service+ | AspectJ语法 |
regex | org\.example\.Default.* | Regelar Expression |
custom | org.example.MyTypeFilter | Spring3新增自訂Type,实作org.springframework.core.type.TypeFilter |