2

Is there any difference between behaviour of @Configuration and @Componentannotation in Spring framework?

Is there any situation when changing @Configuration to @Component will change program's behaviour?

I did a few experiments and from what I see so far, they always work the same. Notice that I'm interested specifically in the difference of behaviour - I already know that the two annotations are usually used in different situations.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Ses "@Bean lite mode" in https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html – JB Nizet Dec 29 '19 at 09:58

2 Answers2

3

Your @Configuration class can be annotated also with @ComponentScan

we use the @ComponentScan annotation along with @Configuration annotation to specify the packages that we want to be scanned

If you change to @Component it won't work as expected

See also difference between @Configuration and @Component

@Configuration is also a @Component but a @Component cannot act like a @Cofinguration

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
2

While they both make annotated classes beans, they serve different purposes.

Treat a class with @Configuration as a part of your application context where you define beans. Usually, you have @Bean definitions in your @Configuration class.

@Component annotation, on the other hand, means that your class IS a bean itself and that it.

So, for example you need a bean MyService. You can define it in two ways:

@Configuration
public class MyAppConfig {

   @Bean
   public MyService myService(){
      return new MyServiceImpl();
   }
}

or just

@Component
public class MyServiceImpl {
   ...
}

So, when you use your @Configuration as a configuration, adding things specific to it (@ComponentScan, @Bean, ...) it would have a different behaviour and it won't work with just @Component instead.

phil_g
  • 516
  • 6
  • 13