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

Hor*_*ace 15 java spring

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

<context:component-scan base-package="com.fooapp.mainpackage, 
com.fooapp.mainpackage.subpackage1, 
com.fooapp.mainpackage.subpackage2, 
com.fooapp.mainpackage.subpackage3" />
Run Code Online (Sandbox Code Playgroud)

ska*_*man 23

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

<context:component-scan base-package="com.fooapp.mainpackage"/>
Run Code Online (Sandbox Code Playgroud)

这样可以轻松快速地自行验证 - 您是否尝试过?

  • 非常正确,但是如果你想要基于层进行区分,那么你总是可以做`<context:component-scan base-package ="com.fooapp.mainpackage.service"/>等其他层`,只是一个想法 (2认同)

dan*_*nik 5

另外我想补充一点,在默认情况下,有注解的类@Component@Repository@Service@Controller,或自定义的注释,本身使用了@Component注解是唯一检测到的候选组件。

您可以通过应用的自定义过滤器更改此行为 include-filterexclude-filter

例如:

<context:component-scan base-package="com.vanilla">
      <context:exclude-filter 
                type="annotation"
                expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)

它将排除所有@Repository批注。