gpt4 book ai didi

Spring @Component 和 @Bean 注解

转载 作者:行者123 更新时间:2023-12-04 19:32:09 29 4
gpt4 key购买 nike

我相信 @Configuration 注解在 spring 中与 @Bean 注解结合使用时用于替换 xml 配置。但是我看到一段代码,其中 @Bean@Component (在类级别定义)一起使用。这是有效的声明吗?使用带有 @Bean 注释的 @Component 与使用 @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

最佳答案

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

关于Spring @Component 和 @Bean 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38088977/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com