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.

 <context:component-scan base-package="impls.di.annotation.reference"/>

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:

@Component("poem")
public class SimplePoem implements Poem {
    @Value("${poem}")
    String poem;
    public void recite(){
        System.out.println(poem);
    }
}

With our class marked with @Component, component-scan will scan the package and will register it as a bean in the spring context.