2

I am trying to understand the Spring Framework better and my question is basically as the title: What is the benefit of the @Configuration annotation compared to @Service/@Controller/@Repository (or @Component if it is none of the other 3)

As I understand the @Configuration is meant to be a source of beans, but by just marking my classes with for example @Service it becomes a bean and will be picked up by the component scanning?

As I understand it I could either have a @Configuration class that has methods that create a couple of beans (say some services) or just have the classes annotated with @Service directly.

What would be the benefit of having the @Configuration class? Or is the @Configuration mostly useful for some edge cases that I have missed?

I read somewhere that the @Value annotation can be used in a @Configuration annotated class, but I can see in our codebase that we use it in other places, that are not @Configuration marked, so that does not seem to be required

I've been told there is a thread here: What is the difference between @Configuration and @Component in Spring?

But I feel that it only starts explaining what the difference is between the annotations, not WHEN/What the benefit of using one over the other is.

I feel that Michael's comments explain it quite nicely when you would want to use the @Configuration annotation.

Thanks!

  • "*As I understand it I could either have a `@Configuration` class that has methods that create a couple of beans (say some services) or just have the classes annotated with `@Service` directly*" suppose you want to create 2 beans from the same class, possibly with different parameters. It's impossible without `@Configuration`. If your class has 1 instance, use `@Component` and friends – Michael May 25 '21 at 14:35
  • Or suppose you want to create a bean from a class that you can't edit. Perhaps its from a library. It's impossible to add `@Component` to it, but you can make it bean via `@Configuration` – Michael May 25 '21 at 14:37

0 Answers0