spring - ComponentScan.basePackageClasses 与 ComponentScan.basePackages 注册单个 Spring webMVC Controller ?

标签 spring spring-mvc

我想向我的 Spring WebApplicationContext 添加一个特定的 Controller 类。我遇到了以下示例:(它是 Scala 中的,但改编自此处: using ComponentScan or context:component-scan with only one class )

@Configuration 
@ComponentScan(
  basePackages = Array("com.example.controllers"),
  useDefaultFilters = false,
  includeFilters = Array(
    new ComponentScan.Filter(`type` = FilterType.ASSIGNABLE_TYPE,
      value = Array(classOf[com.example.controllers.MyController]))))
class MyConfig {
}

这很好用(但非常冗长)。 但是Spring的@ComponentScan也有basePackageClasses

@Configuration 
@ComponentScan( basePackageClasses=Array(classOf[com.example.controllers.MyController])) 
class MyConfig {
}

对于basePackageClasses,Spring的文档说:

Type-safe alternative to basePackages() for specifying the packages to
scan for annotated components.

但是,虽然第一个 ComponentScan 只正确添加了 com.example.controllers.MyController,但第二个会导致我的所有 @Controller 被扫描并添加!为什么? basePackageClasses有什么用?

例如:https://github.com/mikaelhg/springmvc-example/blob/master/src/main/java/mikaelhg/example/ExampleConfiguration.java 建议使用basePackageClasses来加载单个组件。

<小时/>

更新:

顺便说一句,替换:

@Configuration 
@ComponentScan(
  basePackages = Array("com.example.controllers"),
  useDefaultFilters = false,
  includeFilters = Array(
    new ComponentScan.Filter(`type` = FilterType.ASSIGNABLE_TYPE,
      value = Array(classOf[com.example.controllers.MyController]))))
class MyConfig {
}

@Configuration 
class MyConfig {

  @Bean
  var myController = new com.example.controllers.MyController

}

当添加到 WebApplicationContext 时,MyController 似乎永远不会连接到 servlet(行为更改为 404-NotFound)。

最佳答案

该属性的完整 javadoc 为

Type-safe alternative to basePackages() for specifying the packages to scan for annotated components. The package of each class specified will be scanned.

Consider creating a special no-op marker class or interface in each package that serves no purpose other than being referenced by this attribute.

通过类型安全,包名称的 String 值不会出现任何错误。如果指定了不正确的类,它将在编译时失败。

当您指定basePackageClasses时,Spring将扫描您指定的类的包(和子包)。对于诸如 Controller 、服务等无操作类/接口(interface)来说,这是一个很好的技巧。将所有 Controller 放入包含 Controller 的一个包中类并在 basePackageClasses 中指定您的 Controllers 类。 Spring 会把它们全部捡起来。

您仍然需要指定过滤器。

关于spring - ComponentScan.basePackageClasses 与 ComponentScan.basePackages 注册单个 Spring webMVC Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130166/

相关文章:

java - @ControllerAdvice 异常处理与@ResponseStatus 一起

Spring 更改日期输入格式

java - 从 spring mvc Controller 操作中,如何访问请求/响应?

java - Spring中如何保存URL中传递的参数以供不同 Controller 使用?

java - 使用 Spring Security 登录的链接

java - 如何在 @Component 构造函数中使用 @Inject ed Spring Environment

java - HTTP 状态 404 – 源服务器未找到目标资源的当前表示或不愿意透露该资源的存在

java - Spring 3 和 JPA 使用 JTATransactionManager,但事务管理器无法提交

java - 如何在hibernate中连接多个表

Spring MVC 和 @Validate : Perform validate only on specific condition or if user changes the property