Tuesday 16 April 2024

Spring @Configuration vs @Component

 There is a very subtle difference between them. Let me provide a very quick outlook to this.

Consider the below scenario:

@Configuration
public class MyConfig {

    @Bean
    public ServiceA aService(){
        return new ServiceA();
    }

    @Bean
    public ServiceB bService(){
        return new ServiceB(aService());
    }

}

Note that ServiceB bean has a dependecy on ServiceA and this is not autowired. Instead, the way it's written implies that a new instance is created, which is not actually created by Spring. You, the programmer, did it with the new keyword instead.

So, if we do use @Configuration, then it uses CGLIB proxying, and in this situation it creates a singleton bean managed by the Spring context. If you invoke it multiple times, it returns the same bean that was created by Spring - sort of autowiring effect.

Whereas if you use @Component, it won't do this proxying and will simply return a new instance every time the method is invoked, instead of providing the Spring managed instance. (Remember that a Spring bean is something that is managed by the Spring container, and, as a developer, it's your job is to pull them in, e.g. with @Autowired.

The same @Component effect can be achieved with @Configuration(proxyEnabled= false) (This is also referred to as bean light mode processing). So, in light mode, you would end up doing something like this:

@Configuration(proxyEnabled = false) // Lite mode, same effect as @Component
public class MyConfig {

    @Bean
    public ServiceA aService() {
        return new ServiceA();
    }
    
    @Autowired
    @Bean
    public ServiceB bService(ServiceA aServiceBean){
        return new ServiceB(aServiceBean);
    }

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

No comments:

Post a Comment