@ComponentScan具有多个配置类:基于注释的配置

8 java spring spring-mvc component-scan

根据Spring Doc-

配置组件扫描指令以与@Configuration类一起使用.提供与Spring XML <context:component-scan>元素并行的支持.

在我的春季Web应用程序中,有多个文件被标记@Configuration,以便@component在spring容器中注册bean-

Question1-我们能否用@ComponentScan 在任何的的@Configuration或所有 @Configuration类?

问题2-

我也在春天看过doc

@Configuration
@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyConfiguration extends WebMvcConfigurerAdapter {
...
}
Run Code Online (Sandbox Code Playgroud)

为什么在这里扫描配置类本身.

编辑:基本上我用理解@ComponentScan是:扫描并注册立体式豆(EX- @componant,@Controller,@Services等..),为什么我们正在注册@Configuration的Bean.

The*_*ous 8

对于你的问题1 -

是的,您可以@ComponentScan任何在spring容器中注册配置bean中注册bean.您可以通过以下任何方式将 bean 注册到容器中 -

  1. @Configurationrootcontext或中 注册bean dispatchersevletcontext.
  2. @Configuration在已在容器中注册的bean中导入它.

比方说 - 你有一个MvcConfig班级,你正在扫描组件 -

@ComponentScan(basePackages = {"xxxx","yyyy","zzzz"})
@Configuration
public class MvcConfig  {
....
}
Run Code Online (Sandbox Code Playgroud)

MvcConfig在容器中注册,您必须 -

new AnnotationConfigWebApplicationContext().register(MvcConfig.class);
Run Code Online (Sandbox Code Playgroud)

要么

new AnnotationConfigWebApplicationContext().register(AnotherConfig.class);

@Configuration
@Import({MvcConfig.class})
public class AnotherConfig  {
....
}
Run Code Online (Sandbox Code Playgroud)

对于你的问题2 -

这里spring不仅注册了,MyConfiguration.class而且还包含了MyConfiguration定义的包中存在的所有组件类.