如何使用组件过滤器从组件扫描中排除控制器类?

时间:2017-07-22 17:57:02

标签: java spring

我的项目中有很多控制器类,有些是用@RestController注释的,其余用@Controller和@ResponseBody注释。整个基础包在根上下文Spring配置类和Web应用程序上下文Spring配置类中进行组件扫描。我想在初始化根上下文时使用组件过滤器来停止扫描控制器类。我尝试了以下但它没有按预期工作。我仍然看到Controller类存在于根应用程序上下文中。

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

}

还尝试使用RestController.class但两者都没有运气。我相信Controller.class本身应该可以工作,因为RestController是Controller和ResponseBody的包装器。我的所有控制器类都以类名* Controller结尾,有一种方法可以使用正则表达式来过滤以控制器结尾的类和/或使注释过滤器按预期工作。

2 个答案:

答案 0 :(得分:0)

您可以将excludeFilters与正则表达式结合使用,以指定您不想扫描的控制器:

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

}

答案 1 :(得分:0)

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

了解更多信息,请参阅以下链接:

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

相关问题