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 co
This works in Spring 3.0.5. So, I would think it would work in 3.1
<context:component-scan base-package="com.example">
<context:exclude-filter type="aspectj" expression="com.example.dontscanme.*" />
</context:component-scan>
You can also use @SpringBootApplication, which according to Spring documentation does the same functionality as the following three annotations: @Configuration, @EnableAutoConfiguration @ComponentScan in one annotation.
@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}
It seems you've done this through XML, but if you were working in new Spring best practice, your config would be in Java, and you could exclude them as so:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.example.tool",
excludeFilters = {@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
value = {JPAConfiguration.class, SecurityConfig.class})
})
For Spring 4 I use the following
(I am posting it as the question is 4 years old and more people use Spring 4 than Spring 3.1):
@Configuration
@ComponentScan(basePackages = "com.example",
excludeFilters = @Filter(type=FilterType.REGEX,pattern="com\\.example\\.ignore\\..*"))
public class RootConfig {
// ...
}
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.
I think you should refactor your packages in more convenient hierarchy, so they are out of the base package.
But if you can't do this, try:
<context:component-scan base-package="com.example">
...
<context:exclude-filter type="regex" expression="com\.example\.ignore.*"/>
</context:component-scan>
Here you could find more examples: Using filters to customize scanning