I believe @Configuration
annotation when used in conjunction with @Bean
annotation in spring is used to replace xml configuration. However I saw a piece of code where @Bean
was used in conjunction with @Component
(defined at class level). Is this a valid declaration? Are there any any pros / cons in using @Component
with @Bean
annotation vs using @Configuration
and @Bean
.
EDIT:
Thanks @Sundar & @Biju. I did programmatic call between 2 bean methods under Component class. I saw different object values. However when I used Configuration , I saw the same bean values. Based on what you had explained , I assume a regular method call was made when I used @Component
, whereas when I used @Configuration
, I assume method annotated with @Bean
was treated as a Spring Bean
Code
@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();
}
}
Console Output
com.company.service.CustomerServiceImpl@68bbe345
com.company.service.CustomerServiceImpl@30b8a058
Code
@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();
}
}
Console Output
com.company.service.CustomerServiceImpl@71623278
com.company.service.CustomerServiceImpl@71623278