InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

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

Posted by Scott Delap on Dec 01, 2006

Sections
Architecture & Design,
Development,
Operations & Infrastructure
Topics
Application Servers ,
AOP ,
Java
Tags
Spring
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
}

12 comments

Watch Thread Reply

Bad Groovy Builder example by Colin Sampaleanu Posted
Scripting is probably best by Thom Nichols Posted
Re: Scripting is probably best by Rod Johnson Posted
Re: Scripting is probably best by Rick Hightower Posted
Re: Scripting is probably best by Rod Johnson Posted
Re: Scripting is probably best by Corby Page Posted
Re: Scripting is probably best by Graeme Rocher Posted
Re: Scripting is probably best by ZedroS Schwartz Posted
Re: Scripting is probably best by Jan Berkel Posted
Re: Scripting is probably best by Graeme Rocher Posted
Re: Scripting is probably best by Rusty Wright Posted
Re: Scripting is probably best by Jan Berkel Posted
  1. Back to top

    Bad Groovy Builder example

    by Colin Sampaleanu

    That's not at all a great example of the Groovy Spring Bean builder. Any of the samples on the linked Groovy Builder page above gives a much better feel for the "builder" approach. You should replace the example.

    The same "builder" style is possible in a language like Ruby/JRuby.

    Colin

  2. Back to top

    Scripting is probably best

    by Thom Nichols

    I always thought XML was a bit awkward for configuration. Of course, the main advantage is that you can change the configuration without any compiling! So Java, annotations or not, would seem to be a let-down.

    Groovy would seem to be ideal for the task and is practically a no-brainer to use. Although I agree with the above comment -- the Groovy example in the article is poor. See the examples on the Grails page.

    I have feeling scripting is going to take a bigger role in these types of tasks (build scripts, rules engines, workflow templates) and relegate XML to more of a pure data representation role as it should be.

  3. Back to top

    Re: Scripting is probably best

    by Rod Johnson

    I always thought XML was a bit awkward for configuration. Of course, the main advantage is that you can change the configuration without any compiling! So Java, annotations or not, would seem to be a let-down.

    There are different types of configuration. Much configuration does benefit from being externalized, and XML (and properties files) as provided by Spring provide a great solution there. XML, among other things, has excellent tool support, and is nicely extensible with namespaces (which we've taken advantage of in Spring 2.0).

    However, some configuration is still naturally external to the core business logic, but changes infrequently enough so that a compiled approach is just fine. And static checking as provided by a compiler adds value.

    The Spring container is independent of any particular configuration source. So where I see this going is to assemble contributions from the different configuration requirements applications may have (Java, XML, properties, even database and LDAP) into a single rich component model. So that things that change at different rates are each in an appropriate format, and never need to modify your business object classes to change any configuration.

  4. Back to top

    Re: Scripting is probably best

    by Rick Hightower

    RE: Of course, the main advantage is that you can change the configuration without any compiling! So Java, annotations or not, would seem to be a let-down.

    In practice I don't see the config files being modified much outside of the development effort. They become pretty static for a given application.

    Also, with Eclipse incremental compile what is the disadvantage of putting things in Java. Perhaps you could limit the XML config to things that are likely to need configuration changes (which should be small for most apps that I have seen).

  5. Back to top

    Re: Scripting is probably best

    by Rusty Wright

    I always thought XML was a bit awkward for configuration.

    I don't understand why it's become so fashionable to bash using xml for configuring things. Unlike the so-called Domain Specific Languages, with xml you're more likely to get error messages that tell you what's wrong, rather than syntax errors that the so-called Domain Specific Language is hiding behind.

    I'm not against using Ruby, Groovy, etc. for configuring stuff, but calling these configuration pseudo languages "Domain Specific" when they're really not, bugs me. To me, a true Domain Specific Language is one that has its own parser, and its error messages are specific to the domain it's designed for, and you can't use some other language (i.e., the host language like Ruby or Groovy) accidently or intentionally.

  6. Back to top

    Re: Scripting is probably best

    by Jan Berkel

    Martin Fowler refers to this type of DSL as
    Internal DSLs
    . Basically you get a DSL plus all the features of the base language (no need to reimplement basic structures). This is really powerful, provided that all the developers know the base language, so it is a doubled-edged sword. XML is just the lowest common denominator everyone is familiar with.

  7. Back to top

    Re: Scripting is probably best

    by Rod Johnson

    Rick


    Also, with Eclipse incremental compile what is the disadvantage of putting things in Java. Perhaps you could limit the XML config to things that are likely to need configuration changes (which should be small for most apps that I have seen).

    Yes: as I said, different types of configuration for different purposes.

    Largely static configuration relating to object wiring => Java config
    Not so static configuration relating to object wiring => XML
    Stuff that changes all the time => XML
    Simple values like database urls and passwords => properties files

    Spring + Spring JavaConfig already covers all of this. In the future it would be great to supplement it with more dynamic sources of configuration like database-backed configuration.

  8. Back to top

    Re: Scripting is probably best

    by Corby Page

    More choices for everyone is awesome. But I find it pretty amusing that a lot of the people who are getting so excited about the Java config options are the same people who ranted about how XML config files get too large and out of control.

    For simple configs that make up most of an app, the Java option is more verbose than the XML equivalent. I would love to use Java for some dynamic configuration, but using it as my default configuration option would be FUGLY. Maybe we've forgotten why Spring 1.0 became so much more popular than the traditional Builder pattern.

  9. Back to top

    Re: Scripting is probably best

    by Graeme Rocher


    Largely static configuration relating to object wiring => Java config
    Not so static configuration relating to object wiring => XML
    Stuff that changes all the time => XML
    Simple values like database urls and passwords => properties files


    Unfortunately none of these were good enough for us when doing Grails. The Java configuration option was not out at the time and even if it was it uses annotations, and doesn't cover all the bases.

    With XML sure you get it update and change, but the problem is it is largely a static file. So if you're dealing with multiple environments and a convention-over-configuration approach like we are where you want the logic of the bean wiring to adapt to its environment and the conventions within the project, XML doesn't cut it.

    And if you look at it every project has these same issues and traditionally you get round them by having an XML file for each environment for a single XML file with individual properties files read-in to adapt settings to the environment. However, the level of "adaption" is limited because XML is not a programming language and please don't try to make it one (see the horrors of Ant and XSLT).

    The Groovy "mini-DSL" suites our use case perfect and in fact any use case that wants to use a convention over configuration approach and let the logic within your application adapt to its environment programmatically.

  10. Back to top

    Re: Scripting is probably best

    by ZedroS Schwartz

    Maybe there could be a way to reunite the best of the two worlds, by being able to initialise a config with some XML, update it with Groovy/DSL and then save it again in XML.

    If the XML file could be modified by only one at a time, there would be few issue no ?

  11. Back to top

    Re: Scripting is probably best

    by Jan Berkel

    Maybe there could be a way to reunite the best of the two worlds, by being able to initialise a config with some XML, update it with Groovy/DSL and then save it again in XML.


    i like the idea, that's probably something which should be in the Spring core, say in form of a XMLBeanDefinitionWriter class which is able to serialize a spring config back to XML. as far as i know this doesn't exist at the moment, though.

  12. Back to top

    Re: Scripting is probably best

    by Graeme Rocher

    Maybe there could be a way to reunite the best of the two worlds, by being able to initialise a config with some XML, update it with Groovy/DSL and then save it again in XML.

    If the XML file could be modified by only one at a time, there would be few issue no ?


    We do this with Grails. See grails.org/Runtime+Configuration+Plugins

    Cheers
    Graeme

Educational Content

Jesper Boeg on Priming Kanban

In this interview, Jesper Boeg, author of the new InfoQ book – Priming Kanban, discusses the keys to using Kanban effectively, and how to get started if you are currently using other approaches.

New-age Transactional Systems - Not Your Grandpa's OLTP

John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.

Cool Code

Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.