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

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

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


当前回答

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

什么时候应该使用@Bean?

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

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

其他回答

@Component和@Bean做两件完全不同的事情,不应该混淆。

@Component(以及@Service和@Repository)用于使用类路径扫描自动检测和自动配置bean。在带注释的类和bean之间存在隐式的一对一映射(即每个类一个bean)。这种方法对连接的控制非常有限,因为它是纯声明性的。

@Bean用于显式地声明单个bean,而不是像上面那样让Spring自动执行。它将bean的声明与类定义解耦,并允许您按照自己的选择创建和配置bean。

回答你的问题…

是否有可能重用@Component注释而不是引入@Bean注释?

当然,可能;但他们选择不这样做,因为这两者是完全不同的。春天已经够让人迷惑了,不要再把水弄脏了。

@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-- }

以上答案的附加分数

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

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

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

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

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

每个应用程序都需要哪些

因此,本质上,使用@Bean向上下文添加第三方类。@Component如果它只是在你的单个应用程序中。

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

假设我想要特定的实现依赖于某种动态状态。 @Bean非常适合这种情况。

@Bean
@Scope("prototype")
public SomeService someService() {
    switch (state) {
    case 1:
        return new Impl1();
    case 2:
        return new Impl2();
    case 3:
        return new Impl3();
    default:
        return new Impl();
    }
}

然而,@Component没有办法做到这一点。