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.
对于你的问题1 -
是的,您可以@ComponentScan
在任何在spring容器中注册的配置bean中注册bean.您可以通过以下任何方式将 bean 注册到容器中 -
@Configuration
在rootcontext
或中
注册bean dispatchersevletcontext
.@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
定义的包中存在的所有组件类.
归档时间: |
|
查看次数: |
16829 次 |
最近记录: |