Pragmatic Programmer Issues

java spring config

There is a possibility to configure spring framework only in java. Yep no XML ;).

There is a project spring-java-config. This project aims to provide a way to configure spring without XML. To use it with maven you should add repository to your pom and dependency

<repository>
  <id>spring-milestone</id>
  <name>Spring Milestone Repository</name>
  <url>http://s3.amazonaws.com/maven.springframework.org/milestone</url>
</repository>

<dependency>
   <groupId>org.springframework.javaconfig</groupId>
   <artifactId>spring-javaconfig</artifactId>
   <version>1.0.0.m3</version>
</dependency>

One thing to mention is to setup java 5 compiler, because spring java config use annotation.

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <source>1.5</source>
      <target>1.5</target>
      <encoding>UTF-8</encoding>
    </configuration>
  </plugin>

This config will provide as all the dependencies, we can start to configure our beans. The class which has bean configuration must be annotated by @Configuration annotation, and methods with @Bean annotation is equivalent to element. Resume : klas with @Configuration equals xml file with beans, and method with @Bean equals element.

config class

And the last thing is to use JavaConfigApplicationContext which accepts as constructor class annotated with @Configuration property. Below the main class.

main program

And this is basis, we can probably stop here but I provide some additional information. Depends on method visibility our bean is visible or not in the context.

  • The standard set of *Aware interfaces are supported.
  • You can use scopes, autowire and others features known from xml configuration
  • @Import is equivalent of xml’s <import>, and JavaConfigApplicationContext accepts more than one class as constructor parameter.
  • For web application we can use JavaConfigWebApplicationContext

I’m still watching the future of the project. Stay tuned 😉

Categories