[java] multiple packages in context:component-scan, spring config

How can I add multiple packages in spring-servlet.xml file in context:component-scan element?

I have tried

<context:component-scan base-package="z.y.z.service" base-package="x.y.z.controller" />

and

<context:component-scan base-package="x.y.z.service, x.y.z.controller" />

and

<context:component-scan base-package="x.y.z.service" />
<context:component-scan base-package="x.y.z.controller" />

but got error:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [x.y.z.dao.daoservice.LoginDAO] found for dependency:

This question is related to java spring component-scan

The answer is


Another general Annotation approach:

@ComponentScan(basePackages = {"x.y.z"})

If x.y.z is the common package then you can use:

<context:component-scan base-package="x.y.z.*">

it will include all the package that is start with x.y.z like: x.y.z.controller,x.y.z.service etc.


A delayed response but to give multiple packages using annotation based approach we can use as below:

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


You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:

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

Annotation Approach

@ComponentScan({ "x.y.z", "x.y.z.dao" })

For Example you have the package "com.abc" and you have multiple packages inside it, You can use like

@ComponentScan("com.abc")

<context:component-scan base-package="x.y.z"/>

will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.