Skip to content
This repository has been archived by the owner on Apr 14, 2022. It is now read-only.

Functional Bean Configuration

Arjen Poutsma edited this page Oct 25, 2012 · 10 revisions

#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.

Defining beans using FunctionalConfiguration

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.

FunctionalConfigApplicationContext

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)
}

Convenience bean registration methods

Bean references

BeanLookupFunction

Configuration composition

Importing XML and @Configuration classes

Registering init and destroy functions

Bean Profiles

Clone this wiki locally