Tuesday, May 7, 2013

Component scan support for Spring Scala

Just a few days ago an interesting feature has been committed into the Spring Scala master branch. From this point forward Scala configuration in Spring supports component scanning as the first-class citizen.

Component scanning is an extremely useful feature of Spring Framework which provides the support to dynamically compose the application context, depending on the content of the application classpath. Component scanner basically looks up the classpath in order to find the classes marked with dedicated annotations (such as @Component or @Service). The latter classes are then registered in the application context as the bean definitions. Class eligible for classpath scanning could look as follows.
package org.example;

import org.springframework.stereotype.Component;

@Component
public class MyComponent {}
To enable component scanning in Spring XML configuration, we usually include the <context:component-scan/> element in the wiring file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="org.example"/>

</beans>
People who favor Java Spring configuration style over XML files, usually fall back to the @ComponentScan annotation.
@Configuration
@ComponentScan({"org.example"})
public class MyApplicationConfig {}
Starting from the next milestone of Spring Scala (i.e. 1.0.0.M3) you will be able to use similar component scan syntax in the FunctionalConfiguration classes. In order to take the advantage of new component scanning API in Spring Scala, you need to enhance your configuration with ContextSupport trait.
 
class MyScalaApplicationConfig 
  extends FunctionalConfiguration with ContextSupport {

  componentScan("org.example", "com.example")

}
If you need more strict control over the scanning configuration, you can pass additional options into the componentScan method call.
 
class MyScalaApplicationConfig 
  extends FunctionalConfiguration with ContextSupport {

  componentScan(basePackages = Seq("org.example"),
    scopedProxy = Some(ScopedProxyMode.TARGET_CLASS),
    excludeFilters = Seq(new RegexPatternTypeFilter(Pattern.compile(".*Test")))
  )

}
Until the reference documentation for Spring Scala is released, please refer to the Scaladoc of ContextSupport trait for more details of component scan API.

No comments:

Post a Comment