Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wildcards in base-package attribute in Spring component scanning

Tags:

spring

Can somebody explain what does the ** stand for in context of spring configuration?

<context:component-scan base-package="a.b.**" />

and how does that differ from

<context:component-scan base-package="a.b" />

I couldn't find anything about using wildcards/ant style paths in the base-package attribute of the component-scan element.

Could you also point me to any documentation/source code that would explain using wildcards in the component-scanning attribute? My google-fu is of no use

EDIT: I did some more experiments based on the accepted answer, it all makes sense now knowing how the value of base-package attribute is 'converted' to resource string.

So, I created two Spring managed components

a.b.SpringBean2
a.b.c.d.SpringBean1

SpringBean1 has SpringBean2 injected using @Autowired

so not only this:

<context:component-scan base-package="a.b"/>

and this:

<context:component-scan base-package="a.b.**"/>

work OK in the sense that SpringBean2 can be resolved correctly to be injected in SpringBean1, but these will also work:

<context:component-scan base-package="a.b.**.**.**"/> <!-- as many .** as you want-->
<context:component-scan base-package="a.b**"/>
<context:component-scan base-package="a.b*"/>

This however will fail with NoSuchBeanDefinitionException because of unresolved SpringBean2 type:

<context:component-scan base-package="a.b.*"/>
like image 205
artur Avatar asked Aug 31 '12 13:08

artur


2 Answers

Both mean the same, ultimately a base-package name like a.b gets transformed to a resource lookup with this kind of a resource name - classpath*:/a/b/**/*.class and your first base-package name will be of this resource type: classpath*:/a/b/**/**/*.class, both would end up doing the same thing, getting all class files under a.b package name.

like image 55
Biju Kunjummen Avatar answered Sep 23 '22 00:09

Biju Kunjummen


A more powerful way of defining what to scan and include/exclude is described in the spring framework reference docs. For example you can do this:

<context:component-scan base-package="org.example">
    <context:include-filter type="regex" expression=".*Stub.*Repository"/>
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

See section 3.10.3 of the spring 3.0 ref docs.

You can also do:

<context:component-scan base-package="org.*.example"/>
like image 34
Rich Cowin Avatar answered Sep 23 '22 00:09

Rich Cowin