multiple packages in context:component-scan, spring config
JavaSpringComponent ScanJava Problem Overview
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:
Java Solutions
Solution 1 - Java
The following approach is correct:
<context:component-scan base-package="x.y.z.service, x.y.z.controller" />
Note that the error complains about x.y.z.dao.daoservice.LoginDAO
, which is not in the packages mentioned above, perhaps you forgot to add it:
<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" />
Solution 2 - Java
Annotation Approach
@ComponentScan({ "x.y.z", "x.y.z.dao" })
Solution 3 - Java
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>
Solution 4 - Java
<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.
Solution 5 - Java
Another general Annotation approach:
@ComponentScan(basePackages = {"x.y.z"})
Solution 6 - Java
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"})
Solution 7 - Java
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.
Solution 8 - Java
For Example you have the package "com.abc" and you have multiple packages inside it, You can use like
@ComponentScan("com.abc")