我知道在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用于自动装配组件,而@Bean恰恰是在声明要以不同的方式使用bean。让我来展示它的不同之处。

@ bean

首先,它是一个方法级注释。 其次,通常使用它在Java代码中配置bean(如果不使用xml配置),然后使用类从类中调用它 ApplicationContext。getBean方法。例子:

@Configuration
class MyConfiguration{
    @Bean
    public User getUser() {
        return new User();
    }
}

class User{
}    
        
// Getting Bean 
User user = applicationContext.getBean("getUser");

@ component

这是注释bean的一般方法,而不是专门的bean。 它是一个类级注释,用于避免通过java或xml配置进行所有配置。

我们得到这样的结果。

@Component
class User {
}

// to get Bean
@Autowired
User user;

就是这样。引入它只是为了避免实例化和使用该bean的所有配置步骤。

以上答案的附加分数

假设我们有一个在多个应用程序中共享的模块,它包含一些服务。并不是每个应用程序都需要。

如果在这些服务类上使用@Component并且在应用程序中扫描组件,

我们最终可能会检测到比必要的更多的bean

在这种情况下,您要么必须调整组件扫描的过滤,要么提供即使是未使用的bean也可以运行的配置。否则,应用程序上下文将无法启动。

在这种情况下,最好使用@Bean注释并只实例化那些bean,

每个应用程序都需要哪些

因此,本质上,使用@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.

Bean和Component的区别: