Multiple Packages in Context:Component-Scan, Spring Config

multiple packages in context:component-scan, spring config

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" /> 

How to scan multiple paths using the @ComponentScan annotation?

@ComponentScan uses string array, like this:

@ComponentScan({"com.my.package.first","com.my.package.second"})

When you provide multiple package names in only one string, Spring interprets this as one package name, and thus can't find it.

Putting packages in context:component-scan base-package=/

You can just comma delimit the package names:

<context component-scan base-package="package1, package2"/>

@ComponentScan with multiple configuration class : Annotation Based Configuration

For your Question 1 -

yes, you can register a bean using @ComponentScan in any of the configuration bean which is registered in spring container.you can register a bean into container by any of the following way-

  1. Use @Configuration to register bean in rootcontext or
    dispatchersevletcontext.
  2. Import a class in any @Configuration bean (which is already registered in container).

Let say- you have MvcConfig class in which you are scanning component-

@ComponentScan(basePackages = {"xxxx","yyyy","zzzz"})
@Configuration
public class MvcConfig {
....
}

To register MvcConfig in container you must do-

Either

new AnnotationConfigWebApplicationContext().register(MvcConfig.class);

Or

new AnnotationConfigWebApplicationContext().register(AnotherConfig.class);

@Configuration
@Import({MvcConfig.class})
public class AnotherConfig {
....
}

For your Question 2 -

Here spring is not only registering MyConfiguration.class but also all the component classes those are present in the package in which MyConfiguration defined.

Using @ComponentScan or context:component-scan / with only one class

Simply add is as a bean to your context e.g.

<bean class="my.package.MyClass" />

How can I specify into the Spring XML configuration to perform the component-scan on two different packages?

You can specify multiple packages using comma

<context:component-scan base-package="it.mycompmany.myproject.registrazione,it.mycompmany.myproject.login">
</context:component-scan>


Related Topics



Leave a reply



Submit