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:
With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.
The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.
@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.
In order to activate them, we can add either <context:annotation-config> or <context:component-scan> on top of our XML file. In this section, we'll see how <context:annotation-config> and <context:component-scan> differ from each other in terms of their ways of activating annotations.
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" />
Annotation Approach
@ComponentScan({ "x.y.z", "x.y.z.dao" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With