我知道在spring 2.5中引入@Component注释是为了通过使用类路径扫描来摆脱xml bean定义。

@Bean是在spring 3.0中引入的,可以和@Configuration一起使用,以便完全摆脱xml文件,而使用java配置。

是否有可能重用@Component注释而不是引入@Bean注释?我的理解是,最终目标是在这两种情况下都创建bean。


当前回答

@Bean可以有作用域,而@component不能 如 @Scope(value = WebApplicationContext.)SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)

其他回答

@component and its specializations(@Controller, @service, @repository) allow for auto-detection using classpath scanning. If we see component class like @Controller, @service, @repository will be scan automatically by the spring framework using the component scan. @Bean on the other hand can only be used to explicitly declare a single bean in a configuration class. @Bean used to explicitly declare a single bean, rather than letting spring do it automatically. Its make septate declaration of bean from the class definition. In short @Controller, @service, @repository are for auto-detection and @Bean to create seprate bean from class

    - @Controller
    public class LoginController 
    { --code-- }

    - @Configuration
    public class AppConfig {
    @Bean
    public SessionFactory sessionFactory() 
    {--code-- }

Bean和Component的区别:

这两种方法都旨在在Spring容器中注册目标类型。

区别在于@Bean适用于方法,而@Component适用于类型。

因此,当您使用@Bean注释时,您可以在方法主体中控制实例创建逻辑(参见上面的示例)。而@Component注释则不行。

@Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically. @Component does not decouple the declaration of the bean from the class definition where as @Bean decouples the declaration of the bean from the class definition. @Component is a class level annotation whereas @Bean is a method level annotation and name of the method serves as the bean name. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration. We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container. @Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.

@ component 适用于元件扫描和自动布线。

什么时候应该使用@Bean?

有时自动配置不是一个选项。什么时候?让我们想象一下,您想要连接来自第三方库的组件(您没有源代码,所以不能用@Component注释它的类),因此自动配置是不可能的。

@Bean注释返回一个对象,spring应该在应用程序上下文中将该对象注册为bean。方法主体承担负责创建实例的逻辑。