我想向我的 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/