It's useful when you want Spring to auto scan the classpath and find those configuration beans by itself, instead of explicitly registering them in code.
When you have dozens of beans - as often happens in large web applications - it's no fun registering them all in code.
Spring supports auto scanning for other types of beans too. Prefer to use auto scanning whenever possible.
Karthik Shiraly wrote:It's useful when you want Spring to auto scan the classpath and find those configuration beans by itself, instead of explicitly registering them in code.
If I have understood it correctly then by auto-scan you mean beans discovered via @ComponentScan and when your are saying explicitly registering them in code you referring to the way I have done it in JavaConfig.java file? I shall appreciate if you can explain with a code snippet.
This is explicit registration of JavaConfig as a configuration class:
For auto scanning, you don't have to change anything other than that 1 line.
Let's say your config class package is "springtest". Then auto scanning is done this way by specifying the package instead of the class:
Run this and you'll see the same behaviour is as before, though JavaConfig.class is not explicitly mentioned. That's because Spring is looking for all classes with @Configuration annotation, and registering
them into the context.
Now try adding a new config class springtest.JavaConfig2 which creates another set of beans, annotate that too with @Configuration and see what happens
Next try removing the @Configuration on one of them and see what happens.