如何在<context:component-scan>中包含子包的语法?

15

我正在使用Spring,有很多子包,我是否需要逐个在<context:component-scan>标签中指定它们?

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

25

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

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

这很容易且更快速,你可以自己验证一下 - 你试过了吗?


2
非常正确,但如果您想根据层进行区分,那么您可以始终执行 <context:component-scan base-package="com.fooapp.mainpackage.service"/> 等其他层,这只是一个想法。 - Rachel
根据这份文档 Spring Beans and dependency injection,我们需要将想要注入到 IoC 容器中的代码放在根包中。 - Kay

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>

它将排除所有@Repository注释。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接