我想在Spring WebApplicationContext中添加一个特定的控制器类.我遇到了以下示例:(它在Scala中,但是从这里改编:使用ComponentScan或context:仅使用一个类的component-scan)
@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 {
}
Run Code Online (Sandbox Code Playgroud)
这很好用(但非常冗长).但Spring的@ComponentScan也有basePackageClasses
@Configuration
@ComponentScan( basePackageClasses=Array(classOf[com.example.controllers.MyController]))
class MyConfig {
}
Run Code Online (Sandbox Code Playgroud)
在basePackageClasses中,Spring的文档说:
Type-safe alternative to basePackages() for specifying the packages to
scan for annotated components.
Run Code Online (Sandbox Code Playgroud)
但是,虽然第一个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 {
}
Run Code Online (Sandbox Code Playgroud)
同
@Configuration
class MyConfig {
@Bean
var myController = new com.example.controllers.MyController
}
Run Code Online (Sandbox Code Playgroud)
似乎MyController永远不会被连接到servlet(行为改为404-NotFound) - 当添加到WebApplicationContext时.
Sot*_*lis 16
该属性的完整javadoc读取
basePackages()的类型安全替代方法,用于指定要扫描带注释组件的包.将扫描指定的每个类的包.
考虑在每个包中创建一个特殊的无操作标记类或接口,除了被该属性引用之外没有其它用途.
通过类型安全,您不能使用String包名称的值犯任何错误.如果指定了不正确的类,它将在编译时失败.
指定时basePackageClasses,Spring将扫描您指定的类的包(和子包).这是一个很好的技巧,无操作类/接口,如Controllers,Services等.将所有控制器放在一个包含Controllers类的包中,并在中指定您的Controllers类basePackageClasses.春天会把它们都拿起来.
您仍需要指定过滤器.
| 归档时间: |
|
| 查看次数: |
17197 次 |
| 最近记录: |