Exclude subpackages from Spring autowiring?

HolySamosa picture HolySamosa · May 23, 2012 · Viewed 117.2k times · Source

Is there a simple way to exclude a package / sub-package from autowiring in Spring 3.1?

E.g., if I wanted to include a component scan with a base package of com.example is there a simple way to exclude com.example.ignore?

(Why? I'd like to exclude some components from my integration tests)

Answer

Jonathan W picture Jonathan W · May 23, 2012

I'm not sure you can exclude packages explicitly with an <exclude-filter>, but I bet using a regex filter would effectively get you there:

 <context:component-scan base-package="com.example">
    <context:exclude-filter type="regex" expression="com\.example\.ignore\..*"/>
 </context:component-scan>

To make it annotation-based, you'd annotate each class you wanted excluded for integration tests with something like @com.example.annotation.ExcludedFromITests. Then the component-scan would look like:

 <context:component-scan base-package="com.example">
    <context:exclude-filter type="annotation" expression="com.example.annotation.ExcludedFromITests"/>
 </context:component-scan>

That's clearer because now you've documented in the source code itself that the class is not intended to be included in an application context for integration tests.