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

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

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


当前回答

Bean和Component的区别:

其他回答

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

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

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

回答你的问题…

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

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

You have two ways to generate beans. One is to create a class with an annotation @Component. The other is to create a method and annotate it with @Bean. For those classes containing method with @Bean should be annotated with @Configuration Once you run your spring project, the class with a @ComponentScan annotation would scan every class with @Component on it, and restore the instance of this class to the Ioc Container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean. So when you need to decide which kind of beans you want to create depending upon current states, you need to use @Bean. You can write the logic and return the object you want. Another thing worth to mention is the name of the method with @Bean is the default name of bean.

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

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

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

您可以使用@Bean使现有的第三方类对Spring框架应用程序上下文可用。

@Bean
public ViewResolver viewResolver() {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

通过使用@Bean注释,您可以将第三方类(它可能没有@Component,也可能不使用Spring)包装为Spring bean。然后,一旦使用@Bean包装它,它就是一个单例对象,可以在Spring框架应用程序上下文中使用。现在,您可以使用依赖注入和@Autowired在应用程序中轻松地共享/重用此bean。

因此,可以将@Bean注释看作第三方类的包装器/适配器。您希望使第三方类对Spring框架应用程序上下文可用。

通过在上面的代码中使用@Bean,我显式地声明了一个bean,因为在方法内部,我使用new关键字显式地创建了对象。我还手动调用给定类的setter方法。所以我可以改变前缀字段的值。所以这种手工工作被称为显式创建。如果我对同一个类使用@Component,那么在Spring容器中注册的bean的前缀字段将具有默认值。

另一方面,当我们用@Component注释一个类时,我们不需要手动使用new关键字。它由Spring自动处理。

我看到了很多答案,几乎每个地方都提到@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的所有配置步骤。