Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 930
HolySamosa Avatar asked May 23 '12 17:05

HolySamosa


People also ask

How do you exclude certain beans?

You need a method with '@Bean' annotation that crate and instance of the class, or annotate the class with '@Componen', '@Service' etc. annotation for annotation scanning to find it ? Does @ComponentScan(excludeFilters = @ComponentScan. Filter(type = FilterType.

How do I exclude a particular class in spring boot?

If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude by using the spring. autoconfigure. exclude property.

What is the use of @SpringBootApplication?

Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.


1 Answers

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.

like image 69
Jonathan W Avatar answered Oct 02 '22 19:10

Jonathan W