springautowired

Exclude subpackages from Spring autowiring?


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)


Solution

  • 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.