Spring 3中@Component和@Configuration之间的区别 [英] difference between @Component and @Configuration in Spring 3
问题描述
我遇到了Spring 3提供的两个注释( @ Component 和 @Configuration )
我在这些之间有点困惑。
这是我读到的@Component
I came across two annotations provided by Spring 3 (@Component and @Configuration)
I am a bit confused between these.
Here is what I read about @Component
将此context:component放在bean配置文件中,这意味着,
在Spring中启用自动扫描功能。 base-package表示
你的组件存储在哪里,Spring将扫描这个文件夹,
找出bean(用@Component注释)并在
Spring容器中注册。
Put this "context:component" in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.
所以我想知道@Configuration的用途是什么,如果@Controller将注册我的bean而不需要在spring配置xml文件中声明它们
So I am wondering what is the use of @Configuration then if @Controller will register my beans without the need to declare them in spring configuration xml file
推荐答案
@Configuration
是基于Java的配置机制的核心它是在Spring 3中引入的。它提供了基于XML的配置的替代方案。
@Configuration
is the heart of the Java-based configuration mechanism that was introduced in Spring 3. It provides an alternative to XML-based configuration.
因此以下2个片段是相同的:
So the 2 following snippets are identical:
<beans ...>
<context:component-scan base-package="my.base.package"/>
... other configuration ...
</beans>
和:
@Configuration
@ComponentScan(basePackages = "my.base.package")
public class RootConfig {
... other configuration ...
}
在这两种情况下,Spring都将扫描 my.base.package $ c使用
@Component
注释的类的$ c>和更低版本,或使用 @Component
例如 @Service
。
In both cases Spring will scan in my.base.package
and below for classes annotated with @Component
or one of the other annotations that are meta-annotated with @Component
such as @Service
.
这篇关于Spring 3中@Component和@Configuration之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!