Configuring auto-discovery for spring beans is quite easy and straight forward in the spring application. With auto-discovery in place, you won’t have to manually register the beans in spring config files. This is a way to minimize the xml verbosity in your application. You just need to add the following line to the spring config file and it’s done.
1 2 3 |
[php] <context:component-scan base-package="impls.di.annotation.reference"/> [/php] |
the above line make spring scan through the edu.jft.prashant.utils package and will register the classes as beans that are annotated with:
- @Component
- @Controller
- @Repository
- @Service
- Any custom annotation that is itself annotated with @Component.
So, let’s modify the SimplePoem in this example for auto-discovery. Annotate it with @Component like:
1 2 3 4 5 6 7 8 9 10 |
[php] @Component("poem") public class SimplePoem implements Poem { @Value("${poem}") String poem; public void recite(){ System.out.println(poem); } } [/php] |
With our class marked with @Component, component-scan will scan the package and will register it as a bean in the spring context.
Trackbacks/Pingbacks