如何在context:component-scan
元素的spring-servlet.xml文件中添加多个包?
我试过了
<context:component-scan base-package="z.y.z.service" base-package="x.y.z.controller" />
Run Code Online (Sandbox Code Playgroud)
和
<context:component-scan base-package="x.y.z.service, x.y.z.controller" />
Run Code Online (Sandbox Code Playgroud)
和
<context:component-scan base-package="x.y.z.service" />
<context:component-scan base-package="x.y.z.controller" />
Run Code Online (Sandbox Code Playgroud)
但得到了错误:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [x.y.z.dao.daoservice.LoginDAO] found for dependency:
Run Code Online (Sandbox Code Playgroud) 我使用spring组件扫描来自动检测bean:
@ComponentScan({"com.org.x, com.org.y"})
Run Code Online (Sandbox Code Playgroud)
问题是我想要com.org.x
扫描所有类,但我想要一个单独的类com.org.y.SomeService.class
,单独扫描com.org.y
我怎样才能做到这一点?
除了使用上下文扫描之外,我如何创建这个bean并注入应用程序上下文?
我想在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 …
Run Code Online (Sandbox Code Playgroud) 我被要求为现有的 SpringBoot 项目创建集成测试,该项目的组织不像我希望的那样模块化。例如,有一个包生成与所有服务关联的所有存储库。这成为一个问题,对我来说,当我试图创建一个@WebMvcTest
测试片,因为当我使用@ComponentScan
,@EnableJpaRepositories
,@EntityScan
看我的目标类它结束了扫描共享同一包中的所有其他不必要的。
由于更改项目结构并不是我自己可以做出的决定,我的问题是是否有可能让我的测试扫描选择一个特定的类并忽略同一个包中的所有其他类?
感谢您的关注