0

Apparently, AnnotationConfigApplicationContext#scan() scans for packages recursively.

I am not sure of it, but one of my @Component classes apparently loaded without being explicitly mentioned anywhere except being inside of subpackage of mentioned package.

So first question: is it true that Spring scans package recursively?

The second question, if it was true, is how to disable this?

Dims
  • 47,675
  • 117
  • 331
  • 600

3 Answers3

0

As noted in Spring @Component API

Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

About scanning and/or annotating configuration & settings check this answer, I can't explain it better

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

About disabling sub-package scanning: I think this answers your question (or the second most voted answer for the question).

Community
  • 1
  • 1
akostajti
  • 2,997
  • 1
  • 14
  • 6
0

In your @Configuration file, it's possible to explicitly define which packages should be scanned via the @ComponentScan annotation:

e.g.

@Configuration
@ComponentScan(basePackages = "my.package.first, my.package.second,
               my.package.etc")

Note however that all @Components within the subpackages of these packages will automatically be included. If you wish to disable this, this can be done by applying a filter to @ComponentScan

i.e.

@ComponentScan(basePackages = "my.package", excludeFilters = 
               @ComponentScan.Filter(type = FilterType.ASPECTJ, 
               pattern = "my.package.*"))