Search code examples
spring-bootcomponent-scanspring-autoconfiguration

Why shall I not component-scan my auto-configuration?


In Spring Boot's documentation it is clearly stated that auto-configurations must be specified via the spring.factories file:

Auto-configurations must be loaded that way only. Make sure that they are defined in a specific package space and that they are never the target of component scanning.

I did try to put a @Component on my auto-configuration class and made sure it will be picked up by component scanning. It seems to work.

While I do think it's bad practice, since it is very unlikely that component scanning will actually pick it up in a real world scenario, I am wondering why the documentation feel so strongly about it. Are there any other dangers that I fail to anticipate, and if so, which?

Edit: In https://youtu.be/jDchAEHIht0?t=734 Stéphane and Brian explain that there are two phases, one called "UserConfiguration Phase" and another "AutoConfiguration Phase". Following that thought would suggest, that using @ComponentScan on an auto-configuration class would move it to the "User Configuration Phase" which would basically break semantics of auto-configuration.

However, I've not been able to break it in my experiments. As long as I keep my @Conditional annotation it seems to work as expected...


Solution

  • It seems to work.

    As you might suspect, there is a good reason for that note to be present in the documentation. The whole point of auto-configuration is that they are processed once the user configuration has been parsed for the simple reason that order is important.

    If you have an application with configuration classes producing a bunch of beans, and you want to make sure a certain bean in an auto-configuration is not created if the user has expressed an opinion, you need to make damn sure that this auto-configuration is processed after the user configuration. The video that you've shared is describing that in more details, I would suggest to watch the complete section.

    Are there any other dangers that I fail to anticipate, and if so, which?

    Hopefully the explanation above and your own edit tell you. Auto-configurations are not user configurations. Declaring them in component scan is textbook of user configuration.