上下文中的多个包:component-scan,spring config

Sha*_*ams 178 java spring component-scan

如何在context:component-scan元素的spring-servlet.xml文件中添加多个包?

我试过了

<context:component-scan base-package="z.y.z.service" base-package="x.y.z.controller" />
Run Code Online (Sandbox Code Playgroud)

<context:component-scan base-package="x.y.z.service, x.y.z.controller" />
Run Code Online (Sandbox Code Playgroud)

<context:component-scan base-package="x.y.z.service" />
<context:component-scan base-package="x.y.z.controller" />
Run Code Online (Sandbox Code Playgroud)

但得到了错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [x.y.z.dao.daoservice.LoginDAO] found for dependency:
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 260

以下方法是正确的:

<context:component-scan base-package="x.y.z.service, x.y.z.controller" /> 
Run Code Online (Sandbox Code Playgroud)

注意错误抱怨x.y.z.dao.daoservice.LoginDAO,这不在上面提到的包中,也许你忘了添加它:

<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> 
Run Code Online (Sandbox Code Playgroud)

  • 这个答案意味着base-package的成员没有递归但是有:http://stackoverflow.com/questions/7774295/spring-xml-file-configuration-hierarchy-help-explanation/7774597#7774597.我建议稍微改变一下这个答案,以明确这一点. (5认同)

bio*_*nfo 48

注释方法

@ComponentScan({ "x.y.z", "x.y.z.dao" })
Run Code Online (Sandbox Code Playgroud)


Sea*_*oyd 43

您可以添加多个基础包(请参阅axtavt的答案),但您也可以过滤基础包内扫描的内容:

<context:component-scan base-package="x.y.z">
   <context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)

  • @shams不需要先生我,但如果答案是正确的,你应该将其标记为已接受(点击复选标记) (2认同)

Ire*_*ene 19

<context:component-scan base-package="x.y.z"/>
Run Code Online (Sandbox Code Playgroud)

将工作,因为其余的包是"xyz"的子包.因此,您不需要单独提及每个包.

  • 好!也许这是另一个原因,但这对我来说对于我来说对于portlet的spring mvc并不适用... (2认同)

Rob*_*ide 5

另一种通用的注释方法:

@ComponentScan(basePackages = {"x.y.z"})
Run Code Online (Sandbox Code Playgroud)


San*_*har 5

延迟响应但要使用基于注释的方法提供多个包,我们可以使用如下:

@ComponentScan({"com.my.package.one","com.my.package.subpackage.two","com.your.package.supersubpackage.two"})