user1613360
user1613360

Reputation: 1314

How to exclude Controller classes from Component scan using Component filter?

I have lots of controller classes in my project some annotated with @RestController and the rest annotated with @Controller and @ResponseBody. The whole base package is getting component scanned in both root context Spring config class and and web app context Spring config class. I want to use Component Filters to stop controller classes being scanned when initializing the root context. I tried the following but it didn't work as expected. I still see the Controller classes being present in the root app context.

@Configuration
@ComponentScan(basePackages = {"com.xxx.yyy"}, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)})
public class RootSpringConfig {

}

Also tried using RestController.class and both but still no luck. I believe Controller.class alone should work as RestController is a wrapper around Controller and ResponseBody. I do have all my controller classes ending with *Controller in the class name is there a way to use regex to filter classes which ends with controller and/or make annotation filter work as expected.

Upvotes: 1

Views: 7688

Answers (2)

Anshul Sharma
Anshul Sharma

Reputation: 3512

@ComponentScan(basePackages = "com.concretepage",
     includeFilters = @Filter(type = FilterType.REGEX, pattern="com.concretepage.*.*Util"),
     excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = IUserService.class))

for more you can refer below link:

http://www.concretepage.com/spring/spring-component-scan-include-and-exclude-filter-example-using-javaconfig-and-xml-with-annotation-assignable-aspect-and-regex-filter-types

Upvotes: 1

Raman Sahasi
Raman Sahasi

Reputation: 31891

You can use a combination of excludeFilters with regular expressions to specify controllers that you don't want to scan:

@ComponentScan(basePackages = "com.xxx.yyy",
  excludeFilters = @Filter(type = FilterType.REGEX, pattern="com\\.xxx\\.yyy\\.zzz.*"))  
public class RootSpringConfig {

}

Upvotes: 0

Related Questions