Beyond the FactoryBean
I looked at what a basic FactoryBean
is in my previous post. While FactoryBeans
are important - and knowing what they do can help you navigate the framework more effectively - they're by and large no longer the recommended approach to the task as of Spring 3.0 and the imminent Spring 3.1.
The whole point of a FactoryBean
is to hide the construction of an object - either because it's very complex or because it can't simply be instantiated using the typical constructor-centric approach used by the Spring container (maybe it needs to be looked up? Maybe it needs a static registry method?) Spring has also supported the factory-method
attribute in the XML format. The Java configuration approach offers a conceptually similar (in practice, the result is the same) alternative, but features a more concise, type-safe alternative.
Spring 3.0 saw the introduction of Java configuration which lets you define beans using Java. For instance, to register a regular javax.sql.DataSource
with Spring in XML, you will more than likely delegate to a properties file for the sensitive configuration information (like a database password) and use Spring to instantiate the javax.sql.DataSource
, like this:
<beans ...>
<context:property-placeholder location = "ds.properties" />
<bean id = "ds" class = "a.b.c.MySqlDataSource">
<property name = "user" value = "${ds.user}"/>
<property name = "password" value = "${ds.password}"/>
</bean>
</beans>
This is a simple bean, and translates naturally into Java configuration. It would look like this:
import a.b.c.* ;
@Configuration
@PropertySource("ds.properties")
public class MyConfiguration {
@Inject private Environment env ;
@Bean public MySqlDataSource ds(){
MySqlDataSource ds = new MySqlDataSource () ;
ds.setUser( env.getProperty("ds.user") );
ds.setPassword( env.getProperty("ds.password…