New for Spring 3.1.0.M1: @ComponentScan

Spring 3.1.0.M1 was just released yesterday with a slew of new features, but one of them is something I have been wanting for quite a long time. In Spring 2.5 the concept of component-scan was introduced to lessen the burden of XML configuration (thank God!). This allowed one to simply define a package to scan for components and beans annotated @Repository, @Component, @Service, or @Controller would automatically get registered in the application context.

Spring 3 took this a step further by allowing Java based configurations but with one small caveat: the java based configuration didn’t support component scan. The only way to use component scan from within java configuration would be to define an XML file with the component-scan related configuration in it and then do a @ImportResource(“classpath:whatever.xml”) in the Java config. Thankfully, as of yesterday this is no more and I will illustrate how to do it.

First off you’ll need to include spring 3.1.0.M1 from the milestone releases in your favorite build script. Here’s my gradle file:

Now let me quickly define the domain. It includes a simple domain type (Message) with a repository to look them up plus a little class that does something using the repository. Here they are:

And finally the java based configuration (taking advantage of @PostConstruct to “do something” on initialization versus having a main method doing work):

Pretty nifty. You can also include all the other usual features that component scan has (such as inclusion and exclusion filters) within the annotation. It is definitely refreshing to be able to retire the last piece of XML I was required to use in my spring enabled applications. :)