Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


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">
Rod Johnson
<bean id="book" class="Book" scope="prototype">
Expert One-on-One J2EE Design and Development
<property name="author" ref="rod">

and the same with Java configuration:

public class MyConfig {
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."" = "create-drop"
else if(dataSource.dbCreate) {
hibProps."" = 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