【发布时间】: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