Thursday, September 4, 2014

Difference between @Component and @Configuration?

@Component and @Configuration are indeed very different types of annotations.
@Component and similar annotations (@Service@Repository, etc. )and its JSR-330 counterpart @Named allow you to declare beans that are to be picked up by autoscanning with<context:component-scan/> or @ComponentScan they register the bean definition for the classes, so they are roughly equivalent to declaring the specified beans with the <bean ... /> tag in XML. This bean types will adhere to the standard proxy creation policies.
@Configuration annotation was designed as the replacement of the XML configuration file. To create @Configuration annotated beans, Spring will always use CGLIB to subclass the @Configurationannotated class, overriding its @Bean annotated method to replace it with the bean lookup method to make singleton beans to be created only once. (Spring does not use CGLIB to intercept internalmethod calls of normal Spring beans, it creates a separate instance of proxy instead(same way like JDK proxy does). Doing so allows to use proxies to avoid cardinality mismatch - for example a proxy singleton can fetch current session bean, which is not possible with class inheritance only. ). Despite that, @Configuration annotated classes are still able to use annotated(@Autowired@Inject etc.) fields and properties to request beans (and even other @Configuration annotated beans too) from the container.
Example from 4.12.5 section of the documentation
@Configuration
public class AppConfig {

  @Bean
  public ClientService clientService1() {
    ClientServiceImpl clientService = new ClientServiceImpl();
    clientService.setClientDao(clientDao());
    return clientService;
  }
  @Bean
  public ClientService clientService2() {
    ClientServiceImpl clientService = new ClientServiceImpl();
    clientService.setClientDao(clientDao());
    return clientService;
  }

  @Bean
  public ClientDao clientDao() {
    return new ClientDaoImpl();
  }
}
in the example above only one ClientDao instance will be created.

No comments:

Post a Comment