在<context:component-scan>中包含子包的语法是什么?

2022-09-03 12:16:43

我正在使用Spring,并且我有一长串的子包,我是否必须在标签中逐个指定它们?<context:component-scan>

<context:component-scan base-package="com.fooapp.mainpackage, 
com.fooapp.mainpackage.subpackage1, 
com.fooapp.mainpackage.subpackage2, 
com.fooapp.mainpackage.subpackage3" />

答案 1

组件扫描支持包层次结构,因此这应该有效:

<context:component-scan base-package="com.fooapp.mainpackage"/>

这很容易,可以自己验证 - 你试过吗?


答案 2

此外,我还要补充一点,默认情况下,使用 、 或 本身用 @Component 注释的自定义注释的类是唯一检测到的候选组件。@Component@Repository@Service@Controller

您可以通过应用自定义筛选器来更改此行为,这些筛选器是 或include-filterexclude-filter

例如:

<context:component-scan base-package="com.vanilla">
      <context:exclude-filter 
                type="annotation"
                expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

它将排除所有@Repository批注。


推荐