ComponentScan excludeFilters Not Working In Spring 4.0.6.RELEASE

After lot of work and research I noticed that Spring's behavior is little weird in term of component scanning.

Artifacts were like this :

ServiceImpl is the real implementation class which implements Service interface. ServiceMockImpl is the mocked implantation class which implements Service interface.

I wanted to tweak the component scanning so that it only loads the ServiceMockImpl but not ServiceImpl.

I had to add the @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ServiceImpl.class), in the @ComponentScan of test configuration class, to exclude that particular class from component scanning. But both the classes were getting loaded even after doing the above changes and tests were failing.

After lot of work and research I found that the ServiceImpl was getting loaded because of the other class which was getting loaded and has @ComponentScan for all packages on top of in it. So I added the code to exclude the Application class from the component scanning as follows @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class).

After that it worked as expected.

Code like below

@ComponentScan(
    excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = OAuthCacheServiceImpl.class),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Application.class)
    },
    basePackages = {
        "common", "adapter", "admin"
    }
)

I have seen that lot of questions on component scanning are unanswered for long hence I thought to add these details as it may help somebody in the future.

HTH...


At first,Thanks very much about the answers of @Yuriy and @ripudam,but what makes me confused is when my excludeFilters contains Configuration.class I have to use @Import to import the Classe which annotated by @Configuration.I found when i use excludeFilters = {@Filter(type = FilterType.ANNOTATION,value{EnableWebMvc.class,Controller.class}),all works well.The ContextLoaderListener doesn`t regist the Controller at first.

For example

//@Import(value = { SecurityConfig.class, MethodSecurityConfig.class, RedisCacheConfig.class, QuartzConfig.class })
@ComponentScan(basePackages = { "cn.myself" }, excludeFilters = {
        @Filter(type = FilterType.ANNOTATION,value={EnableWebMvc.class,Controller.class}) })
public class RootConfig {
}