根据Spring Doc-
配置与@Configuration类一起使用的组件扫描指令.提供与Spring XML的<context:component-scan>元素并行的支持.
在我的spring Web应用程序中,有多个标记为@Configuration的文件,以便在Spring容器中注册@component bean-
问题1-我们可以在@Configuration类的任何或所有 @Configuration类中使用@ComponentScan 吗? >
问题2
我也在春季看到了文档
@Configuration @ComponentScan(basePackageClasses = { MyConfiguration.class }) public class MyConfiguration extends WebMvcConfigurerAdapter { ... }为什么在这里扫描配置类本身.
基本上,我对@ComponentScan的理解是扫描和注册立体声类型bean(例如-@componant,@Controller,@Services等.),为什么我们要注册@Configuration Bean.
解决方案问题1-
是的,您可以使用@ComponentScan在任何配置在弹簧容器中的配置豆中注册.您可以通过任何方式将Bean注册到容器中以下方式之一-
让我们说-您有要扫描组件的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 { .... }您的问题2-
spring不仅在注册MyConfiguration.class,而且还在注册MyConfiguration的程序包中存在的所有组件类.
As per Spring Doc-
Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's <context:component-scan> element.
In my spring web application there are multiple files those are marked @Configuration,in order to register @component bean in spring container-
Question1- Can we use @ComponentScan in any of the @Configuration class or in all @Configuration classes?
Question2-
Also I seen in spring doc
@Configuration @ComponentScan(basePackageClasses = { MyConfiguration.class }) public class MyConfiguration extends WebMvcConfigurerAdapter { ... }Why here scanning for configuration class itself.
edit: Basically my understanding with @ComponentScan is to scan and register stereo type bean(ex- @componant,@Controller,@Services etc..),why we are registering @Configuration Bean.
解决方案For your Question 1 -
yes, you can register a bean using @ComponentScan in any of the configuration bean which is registered in spring container.you can register a bean into container by any of the following way-
Let say- you have MvcConfig class in which you are scanning component-
@ComponentScan(basePackages = {"xxxx","yyyy","zzzz"}) @Configuration public class MvcConfig { .... }To register MvcConfig in container you must do-
Either
new AnnotationConfigWebApplicationContext().register(MvcConfig.class);Or
new AnnotationConfigWebApplicationContext().register(AnotherConfig.class); @Configuration @Import({MvcConfig.class}) public class AnotherConfig { .... }For your Question 2 -
Here spring is not only registering MyConfiguration.class but also all the component classes those are present in the package in which MyConfiguration defined.
更多推荐
@ComponentScan具有多个配置类:基于注释的配置
发布评论