【问题标题】:Spring @Component & @Bean annotationSpring @Component & @Bean 注解
【发布时间】:2016-10-31 12:49:51
【问题描述】:

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

编辑:

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

代码

@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

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    这是一个有效的声明,但是有一些问题——@Component 中的那个被称为 lite 模式,并且不能轻易地为以这种形式声明的 bean 注入依赖项。建议始终在 @Configuration 带注释的类中使用 @Bean - 这是一个很好的参考 - http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java-basic-concepts

    【讨论】:

    • 谢谢@Biju!我已经更新了我的问题。感谢您的澄清。
    • 无论有没有@Component,行为似乎都是一样的。如果我在使用 Component 注释的类中使用 Bean 与没有注释有什么区别。
    【解决方案2】:

    您可以使用@Component 作为@Configuration 的替代品。是官方suggestion from spring team

    只需在未使用 @Configuration 注释的类上声明您的 @Bean 方法(但通常使用另一个 Spring 原型,例如 @Component)。 只要您不在 @Bean 方法之间进行编程调用,这将同样有效,但条件适用*。

    请参阅此链接中的更多信息。

    http://dimafeng.com/2015/08/29/spring-configuration_vs_component/

    【讨论】:

    • 谢谢@Sundararaj!我已经更新了我的问题。感谢您的澄清。
    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多