BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Using Java, Groovy, or Annotations to Configure Spring Instead of XML

Using Java, Groovy, or Annotations to Configure Spring Instead of XML

Rod Johnson recently blogged on configuring Spring via Java instead of XML. While the implementation uses annotations, it is unique in the fact that they are in a separate configuration class and not in the core business classes themselves. As Rod puts it the Java based configuration option is in essence a DSL for configuration. Here is an example configuration in XML:

<bean id="rod" class="Person" scope="singleton">
<constructor-arg>
Rod Johnson
</constructor-arg>
</bean>
<bean id="book" class="Book" scope="prototype">
<constructor-arg>
Expert One-on-One J2EE Design and Development
</constructor-arg>
<property name="author" ref="rod">
</property>
</bean>

and the same with Java configuration:

@Configuration
public class MyConfig {
@Bean
public Person rod() {
return new Person("Rod Johnson");
}
@Bean(scope = Scope.PROTOTYPE)
public Book book() {
Book book = new Book("Expert One-on-One J2EE Design and Development");
book.setAuthor(rod()); // rod() method is actually a bean reference !
return book;
}
}
As Rod's blog mentions Spring configuration meta data is separate from the meta data parsing allowing varying configuration implementations. In addition to XML and Java other configuration options are popping up such as the Groovy Spring Builder and the Spring Annotation Project. Here is an example of a configuration using the Groovy Spring Builder: :

if(!dataSource) {
hibProps."hibernate.hbm2ddl.auto" = "create-drop"
}
else if(dataSource.dbCreate) {
hibProps."hibernate.hbm2ddl.auto" = dataSource.dbCreate
}
sessionFactory(ConfigurableLocalSessionFactoryBean) {
dataSource = dataSource
if(application.classLoader.getResource("hibernate.cfg.xml")) {
configLocation = "classpath:hibernate.cfg.xml"
}
hibernateProperties = { MapToPropertiesFactoryBean b ->
map = hibProps
}
grailsApplication = ref("grailsApplication", true)
classLoader = classLoader
}
transactionManager(HibernateTransactionManager) {
sessionFactory = sessionFactory
}

Rate this Article

Adoption
Style

BT