Spring @Component & @Bean annotation

mspsb9vt  于 2023-04-28  发布在  Spring
关注(0)|答案(3)|浏览(115)

我相信@Configuration annotation在与spring中的@Bean annotation结合使用时,是用来替换xml配置的。然而,我看到了一段代码,其中@Bean@Component(在类级别定义)结合使用。这是一个有效的声明吗?使用带有@Bean注解的@Component与使用@Configuration@Bean相比有什么优点/缺点吗?

编辑:

谢谢@Sundar和@Biju。我在Component类下的两个bean方法之间进行了编程调用。我看到了不同的对象值。但是,当我使用Configuration时,我看到了相同的bean值。根据您所解释的,我假设在使用@Component时进行了常规方法调用,而在使用@Configuration时,我假设使用@Bean注解的方法被视为SpringBean

编码

@Component
public class AppConfig {

    @Bean(name="customerService")
    public CustomerService getCustomerService(){
        System.out.println(getService());
        System.out.println(getService());
        return getService();
    }

    @Bean
    public CustomerService getService(){
        return new CustomerServiceImpl();
    }
}

控制台输出

com.company.service.CustomerServiceImpl@68bbe345
com.company.service.CustomerServiceImpl@30b8a058

编码

@Configuration
public class AppConfig {

    @Bean(name="customerService")
    public CustomerService getCustomerService(){
        System.out.println(getService());
        System.out.println(getService());
        return getService();
    }

    @Bean
    public CustomerService getService(){
        return new CustomerServiceImpl();
    }
}

控制台输出

com.company.service.CustomerServiceImpl@71623278
com.company.service.CustomerServiceImpl@71623278
9cbw7uwe

9cbw7uwe1#

这是一个有效的声明,但是也有一些捕获-@Component中的一个被称为lite-mode,并且不能轻松地为以这种形式声明的bean注入依赖项。建议总是在@Configuration注解的类中使用@Bean-这里有一个很好的参考- www.example.com

l0oc07j2

l0oc07j22#

您可以使用@Component作为@Configuration的替代方案。官方suggestion from spring team
只需在没有使用@Configuration注解的类上声明@Bean方法(但通常使用另一个Spring原型,例如。例如@Component)。只要你不在你的@Bean方法之间进行编程调用,这就可以正常工作,但有条件 *。
请参阅此链接中的更多信息。
http://dimafeng.com/2015/08/29/spring-configuration_vs_component/

dl5txlt9

dl5txlt93#

https://www.learnjavaupdate.com/2023/04/difference-between-bean-and-component.html
1.用途:@Bean用于显式声明单个bean。它通常用于配置不受Spring控制的第三方对象,或者创建需要一些定制的bean,这些定制超出了使用组件扫描所能实现的范围。另一方面,@Component用于自动检测和注册应用程序上下文中标记为组件的所有类。
1.配置:使用@Bean定义的bean通常在使用@Configuration注解的配置类中创建。这些类包含返回由Spring容器管理的bean示例的方法。相比之下,@Component用于将任何类标记为可以注入到其他对象中的Spring托管组件。
1.作用域:@Bean可用于配置bean作用域,而@Component不提供此功能。这意味着使用@Bean创建的bean可以用特定的作用域来定义,例如原型或单例,而使用@Component创建的bean通常默认为单例。
1.灵活性:@Bean提供了比@Component更大的灵活性,因为它允许编程示例化和配置bean,以及对bean生命周期的更多控制。另一方面,@Component更简单,更具声明性,允许Spring自动检测和管理组件,而无需任何显式配置。

相关问题