-
Notifications
You must be signed in to change notification settings - Fork 124
Functional Bean Configuration
#Functional Bean Configuration
As an alternative to defining beans in XML, Spring Scala offers an alternative that uses Scala classes instead of XML files to configure your Spring beans. This approach is similar to using @Configuration in standard Spring, except that it is based on functions rather than annotations.
To create a functional Spring configuration, you simply have to mix in the FunctionalConfiguration
trait into your configuration class.
Beans are defined by calling the bean
method on the trait and passing on a function that creates the bean.
In its simplest form, a functional configuration will look something like the following:
class PersonConfiguration extends FunctionalConfiguration {
bean() {
new Person("John", "Doe")
}
}
This configuration will register a Person bean under a auto-generated name. The preceding configuration is exactly equivalent to the following Spring XML:
<beans>
<bean class="Person">
<constructor-arg value="John"/>
<constructor-arg value="Doe"/>
</bean>
</beans>
Of course, you can also register a bean under a specific name, provide aliases, or set the scope:
class PersonConfiguration extends FunctionalConfiguration {
bean("john", aliases = Seq("doe"), scope = BeanDefinition.SCOPE_PROTOTYPE) {
new Person("John", "Doe")
}
}
This configuration will register a Person under the names "john" and "doe", and also sets the scope to prototype.
In much the same way that Spring XML files are used as input when instantiating a ClassPathXmlApplicationContext
and @Configuration
classes are used for the AnnotationConfigApplicationContext
, a FunctionalConfiguration
can be used as input when instantiating an FunctionalConfigApplicationContext:
object PersonConfigurationDriver extends App {
val applicationContext = new FunctionalConfigApplicationContext(classOf[PersonConfiguration])
val john = applicationContext.getBean(classOf[Person])
println(john.firstName)
}