InfoQ

News

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

Posted by Scott Delap on Dec 01, 2006 09:30 PM

Community
Java
Topics
AOP,
Application Servers
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

Reply

Bad Groovy Builder example by Colin Sampaleanu Posted Dec 1, 2006 1:40 PM
Scripting is probably best by Tom Nichols Posted Dec 2, 2006 1:09 PM
Re: Scripting is probably best by Rod Johnson Posted Dec 3, 2006 11:07 AM
Re: Scripting is probably best by Rick Hightower Posted Dec 3, 2006 6:08 PM
Re: Scripting is probably best by Rod Johnson Posted Dec 4, 2006 8:07 AM
Re: Scripting is probably best by Corby Page Posted Dec 4, 2006 9:04 AM
Re: Scripting is probably best by Graeme Rocher Posted Dec 5, 2006 3:30 AM
Re: Scripting is probably best by ZedroS Schwartz Posted Dec 6, 2006 4:24 AM
Re: Scripting is probably best by Jan Berkel Posted Dec 6, 2006 10:58 AM
Re: Scripting is probably best by Graeme Rocher Posted Dec 8, 2006 4:15 AM
Re: Scripting is probably best by Rusty Wright Posted Dec 3, 2006 11:03 PM
Re: Scripting is probably best by Jan Berkel Posted Dec 4, 2006 8:00 AM
  1. Back to top

    Bad Groovy Builder example

    Dec 1, 2006 1:40 PM 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

    Dec 2, 2006 1:09 PM by Tom 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

    Dec 3, 2006 11:07 AM 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

    Dec 3, 2006 6:08 PM 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

    Dec 3, 2006 11:03 PM 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

    Dec 4, 2006 8:00 AM 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

    Dec 4, 2006 8:07 AM 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

    Dec 4, 2006 9:04 AM 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

    Dec 5, 2006 3:30 AM 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

    Dec 6, 2006 4:24 AM 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

    Dec 6, 2006 10:58 AM 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

    Dec 8, 2006 4:15 AM 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 http://grails.org/Runtime+Configuration+Plugins Cheers Graeme

Exclusive Content

Advanced Threat Modeling

John Steven talks about modeling security threats as a way to secure a system while designing its architecture. John focuses on authentication, authorization and session management.

Typemock: Past, Present and Future

Eli Lopian of Typemock answers a few questions on Typemock origins and where Typemock is headed.

Agile in Practice: What Is Actually Going On Out There?

Scott Ambler talks about actual data resulting from surveys made during 2006-2008, showing how Agile is perceived and implemented within organizations.

Building Smart Windows Applications

From QCon 2008, Daniel Moth presents on using Visual Studio 2008 and .NET 3.5 to create compelling rich Windows applications.

Joshua Kerievsky about Industrial XP

Joshua Kerievsky, founder of Industrial Logic, talks about Industrial Extreme Programming which extends XP by including practices dealing with management, customers and developers.

Jeff Barr Discusses Amazon Web Services

Amazon Web Services (AWS) Evangelist Jeff Barr discusses SimpleDB, S3, EC2, SQS, cloud computing, how different Amazon services interact, origins of AWS, AWS globalization and the March AWS outage.

More Than Just Spin (Up) : Virtualization for the Enterprise and SaaS

Cloud services have helped bring virtualization to the forefront. Its full power however, also includes other benefits such as high availability, disaster recovery, and rapid provisioning.

Ruby Beyond Rails

John Lam talks about his path to dynamic languages, some of the problems of making IronRuby run fast, and how the DLR helps with implementing languages.