Search code examples
springinitializationcomponent-scan

Spring Documentation for Component Scan versus Configuration


I've searched for an answer to this question but my search voodoo must be a little off.

At work I've noticed there's a preference to use Spring Configuration and @Beans to initialise our Java objects. While there is no problem with this approach I thought switching over to @Component (with ComponentScan) might

  1. Slightly simplify the code
  2. Put us more inline with good Spring practices

But, thinking about it, I'm having trouble justifying why I consider it a good practice. My understanding of @Bean is that it's useful for initialising legacy or non-Springified, code. That may be causing me to consider @Component as a good practice.

An advantage to the @Bean approach is that it centralises the initialisation. This is a little easier to understand in contrast to @Component which is not as immediately intuitive.

Does Spring have any good documentation on the pros and cons of each approach? Or a best practices guide for this topic?


Solution

  • @Configuration class with @Bean-s inside it is called "Java based configuration". And it's more flexible, then "Annotation based configuration" (@Component).

    It is perfectly valid to have Java configuration and annotated component scans in the same project because they server different purposes.

    @Component (@Service, @Repository etc) are used to auto-detect and auto-configure beans.

    @Bean annotation is used to explicitly declare a single bean, instead of letting Spring do it automatically. You can provide more settings to bean instantiated that way.

    You can do the following with @Bean. But, this is not possible with @Component:

    @Bean
    public MyService myService(boolean someCondition) {
        if(someCondition) {
          return new MyServiceImpl1();
        } else {
            return new MyServiceImpl2();
        }
    }