@ComponentScan具有多个配置类:基于注释的配置
根据Spring Doc-
配置组件扫描指令以与@Configuration类一起使用。提供与Spring XML
<context:component-scan>元素平行的支持。
在我的spring Web应用程序中,有多个文件被标记@Configuration,以便将@componentbean 注册到spring容器中-
1-我们可以@ComponentScan 一个@Configuration班级
@Configuration班级中使用吗?
我在spring文件中也看到过
@Configuration@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyConfiguration extends WebMvcConfigurerAdapter {
...
}
为什么在这里扫描配置类本身。
编辑:基本上我用理解@ComponentScan是:扫描并注册立体式豆(EX-
@componant,@Controller,@Services等..),为什么我们正在注册@Configuration的Bean。
回答:
是的,您可以使用@ComponentScan在 配置Bean
来注册Bean。您可以通过以下任何一种方式将Bean注册到容器中: *
- 用于
@Configuration在rootcontext或中 注册beandispatchersevletcontext。 - 将类导入任何
@ConfigurationBean(已在容器中注册)。
假设-您有MvcConfig要扫描组件的类-
@ComponentScan(basePackages = {"xxxx","yyyy","zzzz"})@Configuration
public class MvcConfig {
....
}
要MvcConfig在容器中注册,您必须执行以下操作:
要么
new AnnotationConfigWebApplicationContext().register(MvcConfig.class);要么
new AnnotationConfigWebApplicationContext().register(AnotherConfig.class);@Configuration
@Import({MvcConfig.class})
public class AnotherConfig {
....
}
在这里,spring不仅要注册MyConfiguration.class,还要注册MyConfiguration定义的包中存在的所有组件类。
以上是 @ComponentScan具有多个配置类:基于注释的配置 的全部内容, 来源链接: utcz.com/qa/431776.html
